D41d8cd98f00b204e9800998ecf8427e

This is a rails action that returns an image from the database. So if you go to the address www.example.com/images/person/jack+smith the parameter for class would be "Person" and the parameter ID would be "jack+smith". I want to make it easy to later expand and add new Models so I want it to require the specified model but I feel that these methods could be shortened or made cleaner.

The second cannot function without the third and I don't like either methods.

def images
  image = Kernel.const_get(params[:class].capitalize).find_by_link(params[:id]).image
  if image.nil?
    redirect_to '/images/blank-photo.gif'
  else
    send_data(image, :type => 'image/png', :filename => params[:id] + '.png', :disposition => 'inline')
  end
end

# This Method is slightly different for each Model. This is from the Person Model.
# It takes the input which would be "jack+smith" for example and compares it to each record in the table with its name value which would actually be "Jack Smith".
def self.find_by_link input
  find(:all).each do |p|
    if p.link_name == input
      return p
    end
  end
  return nil
end

def link_name
  name.downcase.gsub " ", "-"
end

Refactorings

No refactoring yet !

727d5785259d057745de13a9f3a713f4

doppler

August 26, 2010, August 26, 2010 04:09, permalink

No rating. Login to rate!

I'll take a stab at this. The :select here works in Postgresql. YMMV.

def images
  image_class = Kernel.const_get(params[:class].capitalize)
  result = image_class.find(
             :first, :select => "lower(replace('#{params[:id]}',' ','-'))"
           )
  if result.nil?
    redirect_to '/images/blank-photo.gif'
  else
    send_data(
      result.image, 
      :type => 'image/png', 
      filename => params[:id] + '.png', 
      :disposition => 'inline'
    )
  end
end
727d5785259d057745de13a9f3a713f4

doppler

August 26, 2010, August 26, 2010 04:13, permalink

No rating. Login to rate!

oops. that :select should be replaced with...

:conditions => ["lower(replace('#{params[:id]}',' ','-')) = ?", params[:id]]

Your refactoring





Format Copy from initial code

or Cancel