Dalla Rosa

Posts tagged accessors

0 notes &

Dynamically adding attribute accessors in Ruby

A simple way for adding attribute accessors to a class dynamically:

class MyClass
  def add_attr(name, value)
    self.class.send(:attr_accessor, name)
    instance_variable_set("@#{name}", value)
  end
end
just call the add_attr method passing the name of the accessor (as a string) and a value that will be assigned to the variable.
You can also turn this in to a module so that you can easily add the functionality to all your classes.
I’m actually using this in a script I made to easily change data in long csv files.
I wanted to be able to convert CSV files into Ruby objects before changing the data, even if the fields change from file to change.
I know some people are gonna say “just use an existing gem or so”, but this is being fun.

Filed under tech ruby programming accessors