【问题标题】:grape each entity in a single file葡萄在一个文件中的每个实体
【发布时间】:2017-04-15 13:09:33
【问题描述】:

我想在葡萄实体文件中有多个类,这是文件夹结构app/api/proj/api/v2/entities/committees.rb

module PROJ::API::V2::Entities
class Committee < Grape::Entity
expose :id

expose :name, :full_name, :email, :tag, :parent_id

expose :country do |entity, option|
  entity.parent.name if entity.parent.present?
end

# include Urls

private
  def self.namespace_path
    "committees"
  end
end

  class CommitteeWithSubcommittees < CommitteeBase
        # include ProfilePhoto 
        expose :suboffices, with: 'PROJ::API::V2::Entities::CommitteeBase'
      end

在 Grape API 内部

present @committees, with: PROJ::API::V2::Entities::Committee

正在工作。但如果我与

present @committees, with: PROJ::API::V2::Entities::CommitteeList

它不工作。但是当我将它移动到实体内名为committee_list.rb 的新文件时它可以工作。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 entity grape-api


    【解决方案1】:

    您的帖子中似乎遗漏了一些关键信息,因为您没有在任何地方定义名为 CommitteeListCommitteeBase 的类。我假设您已经定义了它们并且您没有提供该代码。

    您遇到的问题与 Rails 如何自动加载类有关。这上面有more informationavailable elsewhere,但本质上你应该确保你的类名、模块名、目录名和文件名都匹配。当您将 CommitteeList 类移动到自己的文件时,它起作用的原因是 Rails 能够动态地找到该类。

    我不得不根据您提供的内容进行一些猜测,但您想要的东西看起来像这样:

    # app/api/proj/api/v2/entities/committee.rb
    module PROJ::API::V2::Entities
      class Committee < Grape::Entity; end
    end
    
    # app/api/proj/api/v2/entities/committee_base.rb
    module PROJ::API::V2::Entities
      class CommitteeBase; end
    end
    
    # app/api/proj/api/v2/entities/committee_with_subcommittee.rb
    module PROJ::API::V2::Entities
      class CommitteeWithSubcommittee < CommitteeBase; end
    end
    
    # app/api/proj/api/v2/entities/committee_list.rb
    module PROJ::API::V2::Entities
      class CommitteeList < CommitteeBase; end
    end
    

    请注意,在此示例中,我重命名了一些内容;您的类名应该是单数(committee 不是 committees)并且文件名应该匹配它们,但是进行这种更改可能会导致您的应用程序中出现其他问题。一般来说,you should use singular 而不是复数。

    我建议阅读the Rails guide entry on constants and autoloading 了解更多详情。

    更新:

    在您的要点中,您说当您使用以下代码运行 present @committees, with: PROJ::API::V2::Entities::CommitteeOffice 时会得到 Uninitialized constant PROJ::API::V2::Entities::CommitteeOffice

    # app/api/proj/api/v2/entities/committee_base.rb
    module PROJ::API::V2::Entities
      class CommitteeBase < Grape::Entity; 
        expose :id
      end
      class CommitteeOffice < CommitteeBase; 
        expose :name
      end
    end
    

    您收到此错误是因为 Rails 只会在文件 entities/committee_base.rb 中查找名为 PROJ::API::V2::Entities::CommitteeBase 的类。如果您喜欢为实体类使用单个整体文件,则必须将上述文件命名为 app/api/proj/api/v2/entities.rb

    通过命名文件app/api/proj/api/v2/entities.rb,它告诉Rails“这个文件包含模块Entities和它的所有类。”

    【讨论】:

    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多