你不需要从你的主应用子类化,你可以在主应用程序中挂载单独的 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
我在文件夹中排列文件,相当随意:
# 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
我可能会模仿 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