rails:如何将数据从类变量传递给实例变量

时间:2015-02-04 14:39:17

标签: ruby-on-rails ruby ruby-on-rails-4

我们说我有这个问题。

module Fields
  extend ActiveSupport::Concern

  module ClassMethods
    def add_field(name)
       define_method(name) do
          self.data[name]
        end      
    end
  end
end

要使用它,我会这样做:

class Content < ActiveRecord::Base
   include Fields
   add_field :title
   add_field :body
end

到目前为止一切顺利。现在我想将默认数据填充到新创建的字段中。我需要这样做:

module Fields
  extend ActiveSupport::Concern

  included do
    after_initialize :default_data 
    class_attribute :fields
  end

  def default_data
    self.fields.each do |field|
       self.data[field.to_sym] = "hello"
    end
  end

  module ClassMethods
    def add_field(name)
       define_method(name) do
          self.data[name]
        end
       fields ||= [] 
       fields << name     
    end
  end
end

然而,这不起作用。 self.fields是零。似乎我无法将类方法属性中的数据传递给实例方法。

我想做的是在add_field的定义过程中定义一个常量变量或数据,并在实例上使用该数据。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您想使用带有实例访问者的类属性,您可以使用Active Support&#39; class_attribute

Rails指南中的一个例子:

class A
  class_attribute :x
end

class B < A; end

class C < B; end

A.x = :a
B.x # => :a
C.x # => :a

B.x = :b
A.x # => :a
C.x # => :b

C.x = :c
A.x # => :a
B.x # => :b

A.x = 1

a1 = A.new
a2 = A.new
a2.x = 2

a1.x # => 1, comes from A
a2.x # => 2, overridden in a2