\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
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
-
\$\begingroup\$ Also, if you're using
ActiveRecord
or similar you can doscope.where(klass=>object).to_a
instead ofmap{|d|d}
. \$\endgroup\$kardeiz– kardeiz2013年09月03日 16:47:42 +00:00Commented 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\$Billy Chan– Billy Chan2013年09月03日 16:50:25 +00:00Commented Sep 3, 2013 at 16:50
lang-rb