Refactoring controller code for DRY

I have a bunch of statements like this in my create and update action of my controller:

@company.set_preference(:api_username, params[:company]['api_username']) if params[:company]['api_username']
@company.set_preference(:api_password, params[:company]['api_password']) if params[:company]['api_password']

      

I am wondering how I can refactor them to make my code drier. I am acutely aware that they might belong to a model (models: bold models and skinny controllers), but I'm not sure what to do. Can someone enlighten me?

Thanks in advance for your time,

Woof

+2


source to share


1 answer


Is this repetition @company.set_preference

you are trying to avoid? or repetition params[:company]..

?

How to add a method to your model Company

, for example:

def update_preferences(prefs)
  prefs.each_pair do |pref_name, value|
    set_preference(pref_name.to_sym, value)
  end
end

      

and then calling him



@company.update_preferences(params[:company])

      

You can also add a check to ensure that only the correct settings are set, eg.

VALID_PREFERENCES = ['api_username', 'api_password']

def update_preferences(prefs)
  prefs.each_pair do |pref_name, value|
    set_preference(pref_name.to_sym, value) if VALID_PREFERENCES.include?(pref_name)
  end
end

      

+8


source







All Articles