I have rake tasks importing thousands of records from several different sources and formats and I’m looking to dry up my code after the parsing, where they currently create or update model records using find_or_initialize_by_* dynamic finders.
Essentially, I’d like to be able to pass in the * section of the find_or_initialize_by_* method.
Here is some sudo code to try explain what I want to achieve.
def create_or_update_record(*args)
model = args[0].classify.constantize
identifier = args[1]
attributes = args.extract_options!
XXX = identifier
record = model.find_or_initialize_by_XXX(identifier.to_sym => @identifier_value)
attributes.each do |attribute|
#set value of attribute here
end
record.save
end
Which I would then call from the rake tasks with something like this in the Product import…
create_or_update_record('Product', 'product_id',{
"product_id" => "1",
"product_price" => "2.99"
})
and something like this in the Category import…
create_or_update_record('Category', 'category_id',{
"category_id" => "1",
"category_name" => "Gloves"
})
I’m guessing I need to override and extend the underlying method_missing. Looks pretty complicated from this blog post I found. http://blog.hasmanythrough.com/2006/8/13/how-dynamic-finders-work
Something like this would work:
To create
We’ll send the dynamic finder to the object, and use the existing method missing