I want to create a bunch of methods for a find_by feature. I don't want to write the same thing over and over again so I want to use metaprogramming.
Say I want to create a method for finding by name, accepting the name as an argument. How would I do it? I've used define_method in the past but I didn't have any arguments for the method to take. Here's my (bad) approach
["name", "brand"].each do |attribute| define_method("self.find_by_#{attribute}") do |attr_| all.each do |prod| return prod if prod.attr_ == attr_ end end end Any thoughts? Thanks in advance.
find_by_XXXfor every attribute.self.find_by_nameandself.find_by_brand. While it is possible to create such methods, it is impossible to call them using normal method calling syntax, because.is not a legal character in an identifier. Is there any particular reason why you want to define a method with an illegal name?Productsfor the inventory system of a Toy store. It's for the final project for the Ruby Nanodegree at Udacity.