Saturday 15 February 2014

ruby - Rails - dynamic method creation -


I have two ways that are different from the ActiveRecord class, they are referring:

 < Code> def category_id_find (category_name) category = Category.find_by_name (category_name) if category! = Nil return category.id and refund neil end and brand branding brand (brand) brand = brand (brand) = Brand.find_by_name (brand) if brand! = Neil Returns brand.id other return zero end end   

Now, I know that to find two types, classes and strings in a dynamically created method, then I tried (And unsuccessfully) something like this:

  def id_find (square, to_find) thing = (class.capitalize) .find_by_name (to_find) if thing.id! = The matter of zero return And then zero end end   

which means that I can call id_find (category, "game")

a single, For example, I would like to capture all the different categories from CSV, for example, keep them on a category table, then only the population of each object is populated by the monster CSV file to populate the tables in seeds Must be based on ID from the table of the ones with the If this is understood ...

class in ruby There is a reserved keyword (this is used only for class announcements), so you can not use it for your method parameter name, developers often change it to clothes Protects the original meaning without colliding with. However, in this case, you might be going through a class name as a string, so I will call it class_name .

There is a number of Rails 'ActiveSupport' which is built in the infraction methods that you can use to convert a string to static, depending on how your CSV data looks, Can end with:

  def id_find (class_name, to_find) thing = (class_name.camelize.constantize) .find_by_name (to_find). ..cancel    

No comments:

Post a Comment