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
Best Way to Debug Third-Party Gems in Ruby
How to Configure Capistrano to Use My Rvm Version of Ruby
Relationship Like Twitter Followers/Followed in Activerecord
What Does the "$" Character Mean in Ruby
Ruby on Rails: How to Explicitly Define Plural Names and Singular Names in Rails
How to Convert a Ruby Hash So That All of Its Keys Are Symbols
Error: SASS Installation for Windows
What Are the Differences Between "Private", "Public", and "Protected Methods"
Adding an Action to an Existing Controller (Ruby on Rails)
Libxml2 Missing MAC Os X 10.10
How to Calculate the Distance Between Two Gps Coordinates Without Using Google Maps API
Setting Up Private Github Access with Aws Elastic Beanstalk and Ruby Container
Monkey Patching Devise (Or Any Rails Gem)
Create_Or_Update Method in Rails
Rails 4 Migration: How to Reorder Columns