patternrubyMinor
Selecting records according to an item
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?
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
endSolution
You want to use
Be careful about security, as without the unless this will access any class in your system. This is just an example.
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
endBe 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
endContext
StackExchange Code Review Q#9978, answer score: 6
Revisions (0)
No revisions yet.