将Grape API(非Rails)拆分为不同的文件

tek*_*agi 3 ruby api ruby-grape grape-api

我正在Grape中编写一个API,但它是独立的,没有Rails或Sinatra或任何东西.我想将app.rb文件拆分为单独的文件.我看过如何在葡萄api app中拆分东西?,但这与Rails有关.

我不知道如何使用模块或类来完成这项工作 - 我确实尝试将不同的文件子类化为我的大文件GrapeApp,但这很难看,我甚至不确定它是否正常工作.最好的方法是什么?

我现在有通过文件夹(拆分版本v1,v2等),但仅此而已.

Nei*_*ter 6

您不需要从主应用程序中继承子类,您可以在主要应用程序中安装单独的Grape :: API子类.当然,您可以在单独的文件中定义这些类,并用于require加载您应用可能需要的所有路由,实体和帮助程序.我发现每个"域对象"创建一个迷你应用程序很有用,并加载它们app.rb,如下所示:

  # I put the big list of requires in another file . . 
  require 'base_requires'

  class MyApp < Grape::API
    prefix      'api'
    version     'v2'
    format      :json

    # Helpers are modules which can have their own files of course
    helpers APIAuthorisation

    # Each of these routes deals with a particular sort of API object
    group( :foo ) { mount APIRoutes::Foo }
    group( :bar ) { mount APIRoutes::Bar }
  end
Run Code Online (Sandbox Code Playgroud)

我在文件夹中安排文件,相当随意:

# Each file here defines a subclass of Grape::API
/routes/foo.rb 

# Each file here defines a subclass of Grape::Entity
/entities/foo.rb

# Files here marshal together functions from gems, the model and elsewhere for easy use
/helpers/authorise.rb
Run Code Online (Sandbox Code Playgroud)

我可能会模拟Rails并拥有一个/models/文件夹或类似文件来保存ActiveRecord或DataMapper定义,但是在我当前的项目中以不同的模式为我提供了它.

我的大多数路线看起来非常基本,它们只是调用相关的辅助方法,然后基于它呈现实体.例如,/routes/foo.rb可能看起来像这样:

module APIRoutes
  class Foo < Grape::API
    helpers APIFooHelpers

    get :all do
      present get_all_users_foos, :with => APIEntity::Foo
    end

    group "id/:id" do
      before do
        @foo = Model::Foo.first( :id => params[:id] )
        error_if_cannot_access! @foo
      end

      get do
        present @foo, :with => APIEntity::Foo, :type => :full
      end

      put do
        update_foo( @foo, params )
        present @foo, :with => APIEntity::Foo, :type => :full
      end

      delete do
        delete_foo @foo
        true
      end
    end # group "id/:id"
  end # class Foo
end # module APIRoutes
Run Code Online (Sandbox Code Playgroud)