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

Assigning dynamic attribute list to another class

Person class 具有以下属性:

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

我还有另一个 class 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 属性?

我认为您应该考虑从 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
class PersonFacade
  attr_reader *Person.attribute_names

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