0
\$\begingroup\$

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
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 30, 2013 at 1:30
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
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
answered Aug 30, 2013 at 3:18
\$\endgroup\$
2
  • \$\begingroup\$ Also, if you're using ActiveRecord or similar you can do scope.where(klass=>object).to_a instead of map{|d|d}. \$\endgroup\$ Commented Sep 3, 2013 at 16:47
  • \$\begingroup\$ @kardeiz, yes, nice point. I'm not sure what is the usage so I refactored the logic only. \$\endgroup\$ Commented Sep 3, 2013 at 16:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.