views:

63

answers:

1

Hi,

I have numerous statements like these in both 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'm wondering if how I can refactor these to make my code more dry. I'm acutely aware they may belong in the model (re: fat models and skinny controllers), but am not sure what to do. Can someone enlighten me?

Thanks in advance for your time,

Gav

+6  A: 

Is it the repetition of @company.set_preference that you're trying to avoid? or the repetition of params[:company]..?

How about adding a method to your Company model like:

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

and then calling it with

@company.update_preferences(params[:company])

You could also add a check to ensure only valid preferences are set e.g.

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
mikej
Wow, that seems very powerful! Thank you, you're a star!
Gav