rickypai
rickypai

Reputation: 4016

Referencing method or property with String input

I am writing a rails function which can add either a Car or a Building object to a City object.

The first part of the function is to create the Car or Building object with the given name, then append it to the city's list of cars or buildings.

def addObject(obj_type,obj_name,city_id)
  new_obj = obj_type.constantize.create(:name => obj_name)
  city = City.find(city_id)

  city.obj_type.underscore.pluralize << new_obj
end

With Inflector, the program can use constantize to reference the desired model class.

(thanks to Referencing Model with String input)

Eg:

new_obj = obj_type.constantize.create(:name => obj_name)

However, when trying to access the lists inside the City object,

obj_type.underscore.pluralize

can turn "Car" into "cars"

however, it will only works as a bare string as the follow will not work:

city.obj_type.underscore.pluralize #city.cars desired

will some sort of metaprogramming functions such as eval() be required?

Thank you in advance,

Upvotes: 0

Views: 299

Answers (1)

shingara
shingara

Reputation: 46914

You can do :

city.send(obj_type.underscore.pluralize) << new_obj

In this case you create the method you want call on your city objet and use it by the send

Upvotes: 2

Related Questions