【问题标题】:Split Grape API (non-Rails) into different files将 Grape API(非 Rails)拆分为不同的文件
【发布时间】:2013-07-12 20:15:09
【问题描述】:

我正在用 Grape 编写一个 API,但它是独立的,没有 Rails 或 Sinatra 或任何东西。我想将app.rb 文件拆分为单独的文件。我看过 How to split things up in a grape api app?,但那是 Rails 的。

我不确定如何使用模块或类进行这项工作——我确实尝试将不同的文件子类化到我的大 GrapeApp 中,但这很丑陋,我什至不确定它是否能正常工作。最好的方法是什么?

我目前有按文件夹拆分的版本(v1v2 等),仅此而已。

【问题讨论】:

    标签: ruby api grape grape-api


    【解决方案1】:

    你不需要从你的主应用子类化,你可以在主应用程序中挂载单独的 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
    

    【讨论】:

    • 每个routes文件requiregrape?
    • @tekknolgi:你应该在定义Grape::API 子类之前require 'grape',但如果你不想到处重复,那可以在主要的app.rb 中。
    • 好的,它不会因为未定义的变量和类和东西而出错?
    • @tekknolgi:不应该,但我无法预测您需要做的所有事情。如果您最终得到的结构由于某种原因无法正常工作,那么可能值得再问一个 SO 问题。需求的大多数问题只是将它们按正确的顺序排列。
    • 听起来不错。我会试一试!你在我的 Ruby 问题上无处不在 - 谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2021-07-09
    • 2013-12-18
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多