Adding Attributes to a Ruby Object Dynamically

Set Attribute Dynamically of Ruby Object

Use send:

def set_property(obj, prop_name, prop_value)
obj.send("#{prop_name}=",prop_value)
end

Adding new attribute to Object after it's created using method (Ruby)

Ruby is very lax in this regard. Simply access a variable with @and if it doesn't exist it will be created.

def set_sell_by
@sell_by = value
self
end

Ruby - How to set value for dynamic attribute in class

You should call

a.send "#{attr}=", 1
a.save!

Ruby - dynamically add property to class (at runtime)

The method_missing approach would work, but if you're going to use the accessors a lot after adding them, you might as well add them as real methods, like this:

class Client
def add_attrs(attrs)
attrs.each do |var, value|
class_eval { attr_accessor var }
instance_variable_set "@#{var}", value
end
end
end

This will make them work like normal instance variables, but restricted to just one client.

Is it possible to dynamically call an attribute?

If you're using ActiveRecord, you can use [] to get an attribute.

person = Person.last
attr = "height"
puts person[attr]

But this will only work for attributes in Person.columns_hash and won't work for things like associations.

For that, you'll want to use public_send, like,

person = Person.last
attr = 'height'
puts person.public_send(attr.to_sym)

If you're going to allow a user to select what attribute this is, you'll want to whitelist so someone doesn't attr = params[:attribute] and call ?attribute=destroy and destroy a record. Unless you want them to... :)

Adding dynamic attributes to a Rails model

The write_attribute method updates the attribute in the underlying table. Since your new attributes are dynamic and do not match fields from your model table, no wonder it does not work.

To add attribute dynamically you need to declare it first, and then to call setter as for regular attribute. For example:

attr_name = 'value1'

# Declaring attr_accessor: attr_name
drow.instance_eval { class << self; self end }.send(:attr_accessor, attr_name)

drow.send(attr_name + '=', 'xxx') # setter
drow.send(attr_name) # getter

The property will be saved to the instance variable @value1.

The other way to save dynamic property is to alter that variable directly, without declaring attribute accessor:

drow.instance_variable_set("@#{attr_name}".to_sym, 'xxx') # setter
drow.instance_variable_get("@#{attr_name}".to_sym) # getter


Related Topics



Leave a reply



Submit