<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1117</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1117" rel="self"/>
  <title>Nick</title>
  <updated>Fri Aug 05 12:42:35 -0700 2011</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor571807</id>
    <published>2011-08-05T12:42:35-07:00</published>
    <title>[Ruby] On DRY up a controller action</title>
    <content type="html">&lt;p&gt;@tazsingh I prefer to keep the #render calls as they are, because I'm using the JSend standard:
&lt;br /&gt;&lt;a href="http://labs.omniti.com/labs/jsend" target="_blank"&gt;http://labs.omniti.com/labs/jsend&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here's what I've got now.&lt;/p&gt;

&lt;pre&gt;respond_to do |format|
  if @image.update_attributes params[:product_image]
    format.js   { render :json =&amp;gt; { :status =&amp;gt; 'success', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.actions.updated')} } } 
    format.html { redirect_to main_curate_product_images_path(@product), :notice =&amp;gt; t('product_image.actions.updated') }
  else
    format.js   { render :json =&amp;gt; { :status =&amp;gt; 'fail', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.actions.update_failed')} } } 
    format.html do
      @catalog          = @product.catalog
      @parent_catalogs  = @catalog.ancestors.only :slug, :name
      @crop_data        = @image.crop_data
 
      render :action =&amp;gt; :edit
    end 
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1761-dry-up-a-controller-action/refactors/571807" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor571801</id>
    <published>2011-08-05T11:51:31-07:00</published>
    <title>[Ruby] On DRY up a controller action</title>
    <content type="html">&lt;p&gt;@tazsingh suggested using #respond_to .&lt;/p&gt;

&lt;pre&gt;if @image.update_attributes params[:product_image]
  respond_to do |format|
    format.json { render :json =&amp;gt; { :status =&amp;gt; 'success', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.actions.updated')} } }
    format.html { redirect_to main_curate_product_images_path(@product), :notice =&amp;gt; t('product_image.actions.updated') }
  end
else
  respond_to do |format|
    format.json { render :json =&amp;gt; { :status =&amp;gt; 'fail', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.actions.update_failed')} } }
    format.html do
      @catalog          = @product.catalog
      @parent_catalogs  = @catalog.ancestors.only :slug, :name
      @crop_data        = @image.crop_data

      render :action =&amp;gt; :edit
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1761-dry-up-a-controller-action/refactors/571801" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1761</id>
    <published>2011-08-05T11:13:10-07:00</published>
    <updated>2011-08-05T15:38:18-07:00</updated>
    <title>[Ruby] DRY up a controller action</title>
    <content type="html">&lt;p&gt;Any suggestions for DRYing up this portion of a controller action?&lt;/p&gt;

&lt;pre&gt;if @image.update_attributes params[:product_image]
  if request.xhr?
    render :json =&amp;gt; { :status =&amp;gt; 'success', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.results.reordered')} }
  else
    redirect_to curate_product_images_path(@product), :notice =&amp;gt; t('product_image.actions.updated')
  end 
else
  if request.xhr?
    render :json =&amp;gt; { :status =&amp;gt; 'fail', :data =&amp;gt; {:message =&amp;gt; I18n.t('product_image.results.reorder_failed')} }
  else
    render :action =&amp;gt; :edit
  end 
end&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1761-dry-up-a-controller-action" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor68939</id>
    <published>2008-11-12T17:56:53-08:00</published>
    <title>[Ruby] On Condensing nested conditionals</title>
    <content type="html">&lt;p&gt;Interesting solution, Adam! Much cleaner than my original code. Thanks, mate. Much appreciated!&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/601-condensing-nested-conditionals/refactors/68939" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor68170</id>
    <published>2008-11-12T00:40:28-08:00</published>
    <title>[Ruby] On Condensing nested conditionals</title>
    <content type="html">&lt;p&gt;Hi Adam. You're correct about #deny_access; it uses #redirect_to to halt the filter chain. Your refactoring is great, though it dropped one bit of functionality that's in the original post: redirecting the browser to :back if the requested action doesn't require authentication and hasn't been made public. Any thoughts on how to incorporate that into your suggestion?&lt;/p&gt;

&lt;p&gt;Thanks,
&lt;br /&gt;Nick&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/601-condensing-nested-conditionals/refactors/68170" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code601</id>
    <published>2008-11-11T21:28:53-08:00</published>
    <updated>2008-11-12T17:56:53-08:00</updated>
    <title>[Ruby] Condensing nested conditionals</title>
    <content type="html">&lt;p&gt;The code below works, but feels a bit overly complex, and looks ugly. Any suggestions on how to condense it?&lt;/p&gt;

&lt;pre&gt;## app/controllers/properties_controller.rb
class PropertiesController &amp;lt; ApplicationController
  before_filter :authorise_action

  private

    def authorise_action
      case action_name
      when 'index', 'show', 'map_info_window'
        # Allowed by anyone.
      when 'new', 'create', 'edit', 'update', 'destroy'
        if is_logged_out?
          deny_access :notice =&amp;gt; Phrases.login_required, :redirect_to =&amp;gt; login_url
        elsif is_landlord? or is_admin?
          # Allowed.
        else
          deny_access :notice =&amp;gt; Phrases.access_denied, :store_location =&amp;gt; false
        end
      else
        deny_access :notice =&amp;gt; Phrases.not_public_yet, :store_location =&amp;gt; false, :redirect_to =&amp;gt; :back
      end
    end
end&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/601-condensing-nested-conditionals" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor58697</id>
    <published>2008-11-03T05:46:12-08:00</published>
    <title>[Ruby] On DRY up a controller action</title>
    <content type="html">&lt;p&gt;Hey Adam. There's a Property model, which originally containted what's now the PropertyFilter model. Basically, I needed to do large, multi-param finds, so started building it into the Property model. After a few iterations and  feedback from others, I moved the processing of the search params, the building of the args to #find , and the call to #find out of the Property model and into a new model, PropertyFilter.&lt;/p&gt;

&lt;p&gt;Because PropertyFilter doesn't require data to persist, it inherits from AR::BaseWithoutTable .&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/575-dry-up-a-controller-action/refactors/58697" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor57748</id>
    <published>2008-11-01T17:10:19-07:00</published>
    <title>[Ruby] On DRY up a controller action</title>
    <content type="html">&lt;p&gt;Thanks Jarkko. The action's a lot more concise without those instance variable definitions up top, and the calls to #render_to_string .&lt;/p&gt;

&lt;p&gt;I have a habit of defining variables at the beginning of my methods...Perl's &amp;quot;use strict;&amp;quot; battered that into my head many years ago.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/575-dry-up-a-controller-action/refactors/57748" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor57744</id>
    <published>2008-11-01T16:57:58-07:00</published>
    <title>[Bash] On Groupping with stats</title>
    <content type="html">&lt;p&gt;I'd write a small script for this. I've been using Ruby lately, so here's one solution:&lt;/p&gt;

&lt;pre&gt;## process_stats.rb [ruby]
filename    = 'process.log'
ids         = {}

File.readlines(filename).each do |line|
  id = line.match(/\d+/)[0]
  ids[id] ? ids[id] += 1 : ids[id] = 1
end

ids.sort {|a,b| a[1] &amp;lt;=&amp;gt; b[1]}.reverse.each do |pair|
  puts &amp;quot;#{pair[1]} :#{pair[0]}&amp;quot;
end
&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/576-groupping-with-stats/refactors/57744" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code575</id>
    <published>2008-10-31T20:52:05-07:00</published>
    <updated>2008-11-03T05:46:13-08:00</updated>
    <title>[Ruby] DRY up a controller action</title>
    <content type="html">&lt;p&gt;My Neighbourhood &amp;quot;map_filter&amp;quot; action finds Property objects that match search criteria submitted by the user. It works, but I reckon it could be a bit shorter. Any suggestions?&lt;/p&gt;

&lt;pre&gt;# GET /neighbourhoods/map_filter
def map_filter
  @map_filter_errors  = nil # Stores errors related to a filter request.
  @properties         = nil # Stores the properties that match the filter constraints.

  # Extract the &amp;quot;accessible&amp;quot; attributes from the params.
  property_filter_attributes = AccessibleModelAttributes.extract PropertyFilter, params

  filtered_properties = PropertyFilter.new(property_filter_attributes).properties

  # If properties were returned.
  if filtered_properties[:properties]
    @properties = filtered_properties[:properties]

    @property_data = render_to_string(
      :partial  =&amp;gt; 'properties/map_properties_table',
      :locals   =&amp;gt; {:properties =&amp;gt; @properties}
      ) 

    @number_of_properties_found_sentence = render_to_string :partial =&amp;gt; 'properties/number_of_properties_found'
  else
    @map_filter_errors = filtered_properties[:errors]
  end
end
&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/575-dry-up-a-controller-action" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor56558</id>
    <published>2008-10-30T17:25:04-07:00</published>
    <title>[Ruby] On DRYing/shortening form processing</title>
    <content type="html">&lt;p&gt;Hey Adam, thanks for the refactoring suggestion. It's a bit over my head at the moment, as I've never played with AR named scopes, and I'm not entirely sure what you meant the ItemFilter class to do.&lt;/p&gt;

&lt;p&gt;What I ended up doing was moving #filtered_properties and #filter_* from the Property model into a new model, named PropertyFilter.&lt;/p&gt;

&lt;p&gt;PropertyFilter inherits from ActiveRecord::BaseWithoutTable so that I can use AR's convenient validations, and not save data to a database table.&lt;/p&gt;

&lt;pre&gt;class PropertyFilter &amp;lt; ActiveRecord::BaseWithoutTable
  attr_accessible :price_direction, :price # ...many more attributes...

  column :price_direction,  :string
  column :price,            :integer
  column :bedrooms,         :integer
  # ...many more column definitions...

  valid_price_directions  = ['at most', 'at least']
  # ...many more valid values defined...

  validates_inclusion_of :price_direction,
    :in           =&amp;gt; valid_price_directions,
    :allow_blank  =&amp;gt; true
  # ...many more validations...

  def bedrooms_constraint
    return nil if self.bedrooms.blank?
    {:sql =&amp;gt; 'bedrooms = :bedrooms', :bedrooms =&amp;gt; self.bedrooms.to_s}
  end

  # ...many more _constraint methods...

  def properties
    # ...Call each _constraint method, and build the conditions for #find...

    return {:properties =&amp;gt; Property.find(:all, :bounds =&amp;gt; bounds, :conditions =&amp;gt; [conditions_sql, condition_values])}
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/558-drying-shortening-form-processing/refactors/56558" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code558</id>
    <published>2008-10-24T20:03:05-07:00</published>
    <updated>2008-10-30T17:25:06-07:00</updated>
    <title>[Ruby] DRYing/shortening form processing</title>
    <content type="html">&lt;p&gt;In my Rails app, the Property class method #filtered_properties accepts an arg containing params from an HTTP request, processes the params, and returns an array of properties matching the params.&lt;/p&gt;

&lt;p&gt;I've created separate class methods (#filter_X , where &amp;quot;X&amp;quot; is &amp;quot;price&amp;quot;, &amp;quot;bedrooms&amp;quot;, etc) for processing each parameter, which #filtered_properties calls. However, #filtered_properties is still 120 lines.&lt;/p&gt;

&lt;p&gt;Might you have any suggestions for how to make #filtered_properties and/or #filter_X more DRY and/or shorter?&lt;/p&gt;

&lt;pre&gt;  def self.filter_price(direction, price)
    return nil if direction.blank? or price.blank?
    return {:error =&amp;gt; 'Invalid argument: direction'} unless ['at most', 'at least'].include? direction
    return {:error =&amp;gt; 'Invalid argument: price'}     unless price.to_s =~ /\A[0-9]+\Z/

    case direction
      when 'at most'  then  return  {:sql =&amp;gt; 'price &amp;lt;= :price', :price  =&amp;gt; price.to_s}
      when 'at least' then  return  {:sql =&amp;gt; 'price &amp;gt;= :price', :price  =&amp;gt; price.to_s}
      else                  raise   'Unknown error'
    end
  end

  def self.filter_bedrooms(bedrooms)
    return nil if bedrooms.blank?
    return {:error =&amp;gt; 'Invalid argument: bedrooms'} unless bedrooms.to_s =~ /\A[0-9]+\Z/

    {:sql =&amp;gt; 'bedrooms = :bedrooms', :bedrooms =&amp;gt; bedrooms.to_s}
  end

  #
  # ...Snip. There are several more methods like the ones above...
  #

  def self.filtered_properties(params)
    conditions_string = ''
    conditions_hash   = {}      # Stores the conditions for filtering out properties.
    condition_errors  = []      # Stores errors related to a filter request.

    # Process the &amp;quot;price&amp;quot; and &amp;quot;price_direction&amp;quot; params.
    filtered = filter_price params[:price_direction], params[:price]
    if filtered.blank?      # Do nothing.
    elsif filtered[:error]
      condition_errors &amp;lt;&amp;lt; 'Please provide a number for the price. Eg: 1500'
    else
      conditions_string &amp;lt;&amp;lt; filtered[:sql]
      conditions_hash[:price] = filtered[:price]
    end

    # Process the &amp;quot;bedrooms&amp;quot; param.
    filtered = filter_bedrooms params[:bedrooms]
    if filtered.blank?      # Do nothing.
    elsif filtered[:error]
      condition_errors &amp;lt;&amp;lt; 'Please provide a number for the bedrooms. Eg: 2'
    else
      conditions_string &amp;lt;&amp;lt; ' AND ' &amp;lt;&amp;lt; filtered[:sql]
      conditions_hash[:bedrooms] = filtered[:bedrooms]
    end

    # Process the &amp;quot;bathrooms&amp;quot; param.
    filtered = filter_bathrooms params[:bathrooms]
    if filtered.blank?      # Do nothing.
      puts '&amp;gt; bathrooms is blank'
    elsif filtered[:error]
      condition_errors &amp;lt;&amp;lt; 'Please provide a number for the bathrooms. Eg: 2'
    else
      conditions_string &amp;lt;&amp;lt; ' AND ' &amp;lt;&amp;lt; filtered[:sql]
      conditions_hash[:bathrooms] = filtered[:bathrooms]
    end

    # ...snip...

    return condition_errors unless condition_errors.empty?

    self.find :all, :conditions =&amp;gt; [conditions_string, conditions_hash]

  end # End #filtered_properties&lt;/pre&gt;</content>
    <author>
      <name>Nick</name>
      <email>nick@deadorange.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/558-drying-shortening-form-processing" rel="alternate"/>
  </entry>
</feed>

