Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

How might I refactor this to get rid of all the if-else?

  def self.dispatches_for(object)
    scope = Dispatch.asc(:days)
    if object.class == Habit
      scope.where(:habit=>object).map{|d|d}
    elsif object.class == User
      scope.where(:coach=>object).map{|d|d}
    elsif object.class == Content
      scope.where(:content=>object).map{|d|d}
    end
  end
share|improve this question

1 Answer 1

up vote 3 down vote accepted
def self.dispatches_for(object)
  klass = object.class.to_s.downcase.to_sym
  raise "unacceptable class" unless klass.in? [:habit, :coach, :content]
  scope = Dispatch.asc(:days)
  scope.where(klass=>object).map{|d|d}
end
share|improve this answer
    
beautiful, thanks! –  ming yeow Aug 30 '13 at 5:21
    
Also, if you're using ActiveRecord or similar you can do scope.where(klass=>object).to_a instead of map{|d|d}. –  kardeiz Sep 3 '13 at 16:47
    
@kardeiz, yes, nice point. I'm not sure what is the usage so I refactored the logic only. –  Billy Chan Sep 3 '13 at 16:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.