So, we all strive to reduce duplication (DRY) and other smells, and keep our code as nice and clean as possible. For Ruby code, there are a lot of instruments to detect smells, for example the quite nice Caliber service.
However, it seems that I have a different definition of code duplication than the tools. I think this might be connected to the Ruby way of doing things, where you almost never access a variable directly, but through a method call instead. Consider this snippet from a Rails controller:
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
expire_fragment('layout_header')
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
This is flagged with a code duplication warning, because of the two calls to the "params" method. So my question is, would it really be an improvement to assign the params
to a local variable? I consider the way this is written to be the most clear and concise way to do it, and the fact that params
is a method and not a variable is simple "the cost of doing business" in Ruby.
Am I seeing this the wrong way?
EDIT: In this case, a prettier way might be to do a SiteSettings.update_attributes(params)
style update. Consider, if you will, the same problem in another snippet:
def update
@mailing_list = MailingList.find(params[:id])
if @mailing_list.update_attributes(params[:mailing_list])
flash[:notice] = t:Mailing_list_updated
redirect_to(mailing_lists_path)
...