I use the active record find_or_intialize (similar to find_or_create) in a few places, which leads to annoyingly long non-breakable method names. For example, "find_or_initialize_by_topic_id_and_publish_date_and_publist_id" really messes up my formatting. I know with the normal find method I can supply all this stuff as parameters. Is there a more readable version of this method?
views:
35answers:
1
A:
You could implement missing method to parse the method name and reconstruct the long one from an abbreviated one:
finit_b_tid_n_pubdte_npubid(....)
You just have to establish what each shorthand between the underscores is:
def method_missing(id, *args)
fields_in = id.split(/_/)
fields_out = []
fields.each do |f|
case f
when "finit"
fields_out <<= "find_or initialize"
when "b"
fields_out <<= "by"
when "n"
fields_out <<= "and"
when.....
.....
end
end
send(fields_out.join("_"), args)
end
I didn't run this, but it should be enough to give you the idea.