Vasanthakumar C. wrote:
I have a requirement where the method name of an Object will be
generated and accessed dynamically in code. When I tried to access it
showed me “undefined method”. Am attaching a sample code of what i want
to accomplish:
As well as Steve’s suggestion for this case, there is a general method
available in Ruby for sending messages to invoke methods where the
method name is in a string. The method #send does this:
http://www.ruby-doc.org/core/classes/Object.html#M000334
However:
@user_information = UserInformation.new
@table_fields = UserInformation.find_by_sql(“DESC user_informations”)
Try to avoid embedding SQL in your code if possible. You’ll make it
more readable and more portable (especially if you decide to change your
database at some point). The above will return an array of column
properties which is not what you’re after anyway. To get the column
names for a model, use:
@table_fields = UserInformation.column_names
for table_field in @table_fields
temp = table_field.Field # considering Field is user_name
@user_information.temp = “vasanth”
# referring to @user_information.user_name = “vasanth”
end
If you are using a standard Rails model, then one of your columns will
be called “id” and the above will try to overwrite this (numerical)
value with a string. Not a good idea.
This code is also very model oriented but gives the impression you are
wanting to put this into a controller. Whenever you find yourself doing
model logic like this, re-think your strategy. This sort of stuff
should be in the model. So, if you really want the model to be able to
set all attributes (except “id”!) to a particular string, then in your
model:
def set_to_string new_string
attributes.keys.each do | attr |
self.send “#{attr}=”, new_string
end
end
This form means that any setters you’ve overridden for any reason will
be used and using #attributes to get the names automatically excludes
“id”.
This is, of course, dangerous. It assumes that all your attributes are
string values (does the model have “created_at” and “updated_at”?) and
that if you ever add columns, you’ll want them to get the same
treatment.