active_attr icon indicating copy to clipboard operation
active_attr copied to clipboard

Is defining "dynamic" attributes possible?

Open priverop opened this issue 3 years ago • 1 comments

Hello, I'm considering using this gem but I don't know if this is possible to do:

class Person
  include ActiveAttr::Attributes

  attribute :first_name
  attribute :last_name
  # we retreive data from the database with ActiveRecord
  Languages.all.each do |lang| 
      attribute :"name_#{lang.name}", type: String
  end
end

person = Person.new
person.first_name = "Chris"
person.last_name = "Griego"
person.name_english = "Christian"
person.name_spanish = "Cristian"
person.attributes #=> {"first_name"=>"Chris", "last_name"=>"Griego", "name_english" => "Christian", "name_spanish" => "Cristian"}

I don't know if this is it: https://github.com/cgriego/active_attr/issues/6

priverop avatar Jan 12 '23 15:01 priverop

it should be possible, there is a chicken&egg issue where you need Languages to be loaded earlier. but I still think you can do it.

Also, you might need to wrap the dynamic part in a class << eval block

mathieujobin avatar Oct 30 '23 09:10 mathieujobin