将动态属性列表分配给另一个类

时间:2015-01-02 04:23:12

标签: ruby rails-activerecord

我有Person类,其中包含以下属性:

Person.attribute_names
# => ["id", "first_name", "last_name", "email", "age", "address_1", "address_2", 
#  "city", "state", "country", "is_active", "created_at", "updated_at"] 

我有另一个班级PersonFacade,它应该拥有完全相同的属性。我有这段代码:

class PersonFacade
  attr_list = Person.attribute_names
  attr_reader *attr_list

  def initialize(p_object)
     #p_object.attributes.slice(*Person.attribute_names)
     # Line above is giving me the attributes, but I don't want to manually assign them.
  end
end

如何将Person属性分配给PersonFacade属性?

2 个答案:

答案 0 :(得分:2)

class PersonFacade
  attr_reader *Person.attribute_names

  def initialize(p)
    p.attributes.each { |k,v| self.instance_variable_set("@#{k}", v) }
  end
end

答案 1 :(得分:0)

我认为你应该考虑从Person扩展PersonFacade。这使Person的属性很容易在PersonFacade中可用。

class Person
   @id=nil
   @first_name=nil

   def initialize(id, first_name)
      @id = id
      @first_name = first_name
    end

    attr_accessor :id, :first_name
end

class PersonFacade < Person
end

p = PersonFacade.new(1,"Harry")
print p.first_name