0

我为 rails 编写了一个 gem,以拥有一个小型的 mongoid 购物车。

在它得到的模型中,包括include MongoidCart::ActsAsProduct

class MyProduct
   include Mongoid::Document

   include MongoidCart::ActsAsProduct
end


module MongoidCart
  class CartItem
    include Mongoid::Document

    belongs_to :mongoid_cart_cart, :class_name => 'MongoidCart::Cart'
  end
end


module MongoidCart
  class Cart
    include Mongoid::Document

    field :user_id, type: String

    has_many :cart_items, :inverse_of => :cart, :class_name => 'MongoidCart::CartItem'
    belongs_to :customer, :inverse_of => :carts, :class_name => MongoidCart.configuration.customer_model_name

  end
end

class_name我很难将我Product的班级带入CartItem班级。它应该会自动向MongoidCart::CartItem类添加关系。当我像我一样“硬编码”时:my_product,没有错误。

我怎样才能使:the_class_to_point_to_as_symbol动态?

module MongoidCart
  module ActsAsProduct
    extend ActiveSupport::Concern

    included do

      #adds dynamic association to the CartItem to refer to the ActsAsProduct class
      MongoidCart::CartItem.class_eval(
        'belongs_to :the_class_to_point_to_as_symbol, :class_name => "Product", inverse_of: :cart_item'
      )
    end
  end
 end
4

2 回答 2

0

最后我创建了一个新的类来生成字符串,它被解释class_eval并在范围之外调用它们并将字符串放在一个变量中:

module MongoidCart
  module ActsAsProduct
    extend ActiveSupport::Concern

    included do

      # adds dynamic association to the CartItem to refer to the ActsAsProduct class
      relation_method = MongoidCart::Relation.build_product_relation_string(name)
      MongoidCart::CartItem.class_eval(relation_method)
  end
end



module MongoidCart
  class Relation

    # creates a string which can be implemented in models to provide dynamcic relation
    def self.build_product_relation_string(class_name)
      "belongs_to "+ ":#{class_name.to_s.underscore.to_sym}" + ", :class_name => '#{class_name.constantize}', inverse_of: :cart_item"
    end

  end
end
于 2016-04-01T14:45:12.993 回答
0

selfinsideincluded{}块是包含的类,所以你可以做类似的事情

included do
  MongoidCart::CartItem.add_product_relation(self)
end

MongoidCart::CartItem:

def self.add_product_relation cls
  belongs_to cls.name.to_s.underscore.to_sym, class_name:cls, inverse_of: :cart_item
end
于 2016-04-01T15:21:25.817 回答