Topic: Help with DRY up
I am a newbie trying to DRY up my first application. Going well accept this annoying item (simplified down to problematic code) ...
business_attributes = params[...] # values from a form in a view
business_application = BusinessApplication.find(..) # id from view
business_area = BusinessArea.create! business_attributes
business_application.business_areas << business_area unless @business_application.nil?
Now refactored to make more generic and not tied to any particular models (so I can add as an ApplicationController method and become part of a acts_as helper). This code is part of a set of methods that are used 10's of times across various controllers (the rest successfully DRY'd). target and source have a habtm relationship. The new code is as follows:
target_model_class = Object.const_get(target) # target == 'business_areas' - passed as argument
source_model_class = Object.const_get(source) # source == 'business_applications' - passed as argument
attributes = params[...] # values from a form in a view
source_instance = source_model_class.find(...) # id from view
target_instance = target_model_class.create! attributes
source_instance.method(target) << target_instance unless source_instance.nil?
But gets the following error complaining << method does not exist in line 7 above:
undefined method `<<' for #<Method: BusinessApplication#business_areas>
Have tried using #push instead of << method but with same error. Also tried some poorly constructed #call methods too. I know I'm probably doing something completely wrong around the use of #method.