Set Attribute Dynamically of Ruby Object

Set Attribute Dynamically of Ruby Object

Use send:

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

Ruby - How to set value for dynamic attribute in class

You should call

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

More elegant way of setting an object attribute dynamically from string in Ruby

You can do

[:@web, :@mobile, :@accessible].each do |stylesheet|
@theme.instance_variable_set(stylesheet, "some dynamic value"))
end

This saves the string concatenation and string->symbole conversion, so theoretically it's should be a bit faster.

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... :)

Dynamically updating ActiveRecord object attribute

You can use the ActiveRecord hash interface, which would look like this, using your array variable:

array.each do |field|
thing[field.to_sym] = "I'll tell you later"
end

thing.save

Alternatively, you can use the params hash appraoch. Rails uses the params hash to perform a similar operation. You can simulate this functionality in this way:

array = ['title','date','height']
values = ['King Lear', '2016-05-13', 13.5]
attributes_hash = {}

array.map {|elem| elem.to_sym }.each_with_index do |field, i|
attributes_hash[field] = values[i]
end

thing.update(attributes_hash)

The benefit of this approach is that you can update an entire hash of values at one time. If you want to bypass validations and other checks, you can use update_attributes, instead.

For more information, see:

  • ActiveRecord update method
  • ActiveRecord update_attributes
  • Rails update_attributes without save?

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

How to access Model attributes dynamically in a loop in ruby?

You can do like this:

 item.send((attr + "="), values from some other source)

or:

hash = {}
['item_url','item_url','item_label'].each do |attr|
hash[attr] = value
end
item.attributes = hash


Related Topics



Leave a reply



Submit