Saturday, 15 May 2010

ruby on rails 3 - How to split things up in a grape api app? -



ruby on rails 3 - How to split things up in a grape api app? -

in every examples see, people implement 1 giant api.rb file. ex:

intridea/grape bloudraak/grape-sample-blog-api djones/grape-goliath-example

while approach works fine is, can become crowded , hard maintain split things on app.

for instance, split entities resources, , split resources between different files. examples:

app - api api.rb - entities - weblog.rb - post.rb - comment.rb - resources - weblog.rb - post.rb - comment.rb

now, api.rb like:

class="lang-ruby prettyprint-override">require 'grape' module blog class api < grape::api prefix "api" end end

app/api/entities/post.rb like:

class="lang-ruby prettyprint-override">module blog module entities class post < grape::entity root 'posts', 'posts' expose :id expose :content end end end

app/api/resources/post.rb like:

class="lang-ruby prettyprint-override">module blog class api < grape::api resource :posts nowadays post.all, with: blog::entities::post end desc "returns payment method corresponding id" params requires :id, :type => integer, :desc => "post id." end ':id' nowadays post.find(params[:id]), with: blog::entities::post end end end end

when this, encounter next message:

expected /blog-app/api/resources/post.rb define post

solution (thanks db. , co-workers)

you have alter construction like:

app - api api.rb - resources - post_api.rb

then, in post_api.rb

module blog class resources::postapi < grape::api resource :posts nowadays post.all end end end end

finally, api.rb becomes:

class="lang-ruby prettyprint-override">require 'grape' module blog class api < grape::api prefix 'api' version 'v1', :using => :path format :json mount blog::resources::postapi => '/' end end

now /api/v1/posts should work :)

the class in post.rb should post, not api. can mount post api within class api.

class api < grape::api mount blog::post => '/' end

to avoid confusion set post in resources namespace, or rename postapi.

ruby-on-rails-3 api grape-api

No comments:

Post a Comment