2013-02-13 78 views
14

在我看到的每个例子中,人们只实现了一个巨大的api.rb文件。例如:如何在葡萄api应用程序中分割东西?

虽然这种方法细如,它可以迅速变得拥挤,难以维持,所以我想的东西拆了我应用程序。

例如,我想从我的资源中分割我的实体,然后在不同文件之间分割我的资源。对于例子:现在

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

api.rb会是这样的:

require 'grape' 
module Blog 
    class API < Grape::API 
    prefix "api" 
    end 
end 

应用程序/ API /实体/ post.rb会是这样的:

module Blog 
    module Entities 
    class Post < Grape::Entity 
     root 'posts', 'posts' 
     expose :id 
     expose :content 
    end 
    end 
end 

app/api/resources/post.rb会是这样的:

module Blog 
    class API < Grape::API 
    resource :posts do 
     get do 
     present Post.all, with: Blog::Entities::Post 
     end 

     desc "returns the payment method corresponding to a certain id" 
     params do 
     requires :id, :type => Integer, :desc => "Post id." 
     end 
     get ':id' do 
     present Post.find(params[:id]), with: Blog::Entities::Post 
     end 
    end 
    end 
end 

当我们这样做,我们会遇到以下消息:

预计/blog-app/api/resources/post.rb定义后


解决方案(感谢dB。和我的同事)

你必须结构更改为类似:

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

然后,在post_api.rb

module Blog 
    class Resources::PostAPI < Grape::API 
    resource :posts do 
     get do 
     present Post.all 
     end 
    end 
    end 
end 

最后,API .rb变成:

require 'grape' 
module Blog 
    class API < Grape::API 
    prefix 'api' 
    version 'v1', :using => :path 
    format :json 

    mount Blog::Resources::PostAPI => '/' 
    end 
end 

现在/api/v1/posts应该工作:)

+1

如果我有另一个版本的API - v2并且我想要公开不同的属性内容名称,那么假设我将拥有'''expose:body'''而不是''''expose:content '''与此同时我仍然需要支持v1。我想我会开始将实体放入版本文件夹中,对吗?或者你会如何处理这个设置? – 2015-01-16 01:59:35

回答

7

post.rb中的类应该是Post,而不是API。然后,您可以在类API中安装Post API。

class API < Grape::API 
    mount Blog::Post => '/' 
end 

为了避免混淆,我也将Post放在Resources命名空间中,或者将其重命名为PostAPI。

+0

非常感谢@dB。事实上,你必须为命名空间进行命名空间和重命名,以避免混淆......现在就开始工作吧! – X2theZ 2013-02-13 18:29:18

+0

请注意,您应该可以省略'mount'的右侧,所以只需'mount Blog :: Resources :: PostAPI'应该可以工作,不需要挂载在'/'上。 – 2013-02-13 19:28:36

1

我发现它不工作的路径前缀:

mount Blog::Post => '/blog' 

,如果你想有前缀的路径是行不通的。

使用

namespace :blog do 
    mount Blog::Post 
end 

希望它能帮助!