Reputation: 563
I have a module that has a few methods that help find database entries, and I'm trying to create dynamic methods of this sample method:
def find_by(db_attribute, value)
rows = connection.execute <<-SQL
SELECT #{columns.join ","} FROM #{table}
WHERE #{db_attribute} = #{Record::Utility.sql_strings(value)};
SQL
end
I want to figure out how to get a call object.find_by_*
( * star here being the db_attribute that would normally be in the parameter of find_by
) like this: klass.find_by_name('bob')
to return the same thing as find_by(:name, 'bob')
.
Upvotes: 0
Views: 186
Reputation: 941
A very simple solution
def method_missing(method_name, *args, &block)
if method_name.to_s =~ /^find_by_(.+)$/
find_by($1.to_sym => args) # find_by_name, the $1 is `name`
else
super(method_name, *args, &block)
end
end
Upvotes: 3