HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Selecting records according to an item

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemrecordsaccordingselecting

Problem

I use Ruby 1.8.7. I have a method which selects records according to the item that I pass to the method.

In my opinion, the code is not DRY. Could somebody offer suggestions on refactoring it to make it shorter?

def get_record (id,item)
  case item
   when "category"
      @temp = Category.find(id)
   when "status"
      @temp = Status.find(id)
   when "industry"
     @temp = Industry.find(id)
   end
 return @temp.name if @temp
end

Solution

You want to use classify and constantize:

require 'set'
AUTHORIZED = Set[Product, Status, Industry]
def get_record(id, item)
  model = item.classify.constantize
  raise "Go away, hacker" unless AUTHORIZED.include? model
  model.find(id).name
end


Be careful about security, as without the unless this will access any class in your system. This is just an example.

Code Snippets

require 'set'
AUTHORIZED = Set[Product, Status, Industry]
def get_record(id, item)
  model = item.classify.constantize
  raise "Go away, hacker" unless AUTHORIZED.include? model
  model.find(id).name
end

Context

StackExchange Code Review Q#9978, answer score: 6

Revisions (0)

No revisions yet.