【问题标题】:Two files requiring each other in ruby两个文件在 ruby​​ 中相互需要
【发布时间】:2015-05-02 14:32:14
【问题描述】:

我正在使用 Ruby 和 Grape 构建一个 Web API。我有两个相互需要的类,这会导致出现未初始化的常量类错误。我得到错误的地方是在连接器的实体类中,请参见下面的示例代码,它需要 Card::Entity 在初始化之前。有什么方法可以在不将实体定义移动到另一个文件的情况下解决这个问题?

#card.rb
require_relative 'connector'
require_relative 'caption'

class Card < ActiveRecord::Base

  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :cardtype
    expose :connectors, using: Connector::Entity
    expose :captions, using: Caption::Entity
  end
end

#connector.rb
require_relative 'card'

class Connector < ActiveRecord::Base
  has_one  :card
  has_one  :connected_card, :class_name => "Card", :foreign_key => "connected_card_id"

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :title
    expose :card, using: Card::Entity
    expose :connected_card, using: Card::Entity
  end
end

【问题讨论】:

  • ...我觉得你应该重新设计这部分程序,因为这似乎是更糟糕的症状

标签: ruby grape grape-entity


【解决方案1】:

我对葡萄知之甚少,但这可以通过“预先声明”类来解决:

#card.rb
require_relative 'caption'

class Connector < ActiveRecord::Base
  # empty declaration just to make the import works
end

class Card < ActiveRecord::Base
  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions
  ...
end

不过,我认为 QPaysTaxes 在这里可能有关于设计的有效观点。

【讨论】:

  • 好的,是的,这行得通,但这不是我想要继续使用的解决方案。我按照 QPaysTaxes 的建议做了并重新设计了它。
  • 对我来说很好 - 同意这是在回答“我怎样才能使这项工作”而不是一个有效的解决方案。
猜你喜欢
  • 1970-01-01
  • 2015-06-16
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
  • 2013-07-10
  • 2012-03-16
  • 2015-03-11
  • 2021-05-30
相关资源
最近更新 更多