开发者

Iterating over a collection with multiple types - how do I use type-specific attributes?

I want to iterate over a collection that contains objects of various types. If I want to use a common attribute, it's easy because I don't have to test for type -- they all respond.

But what if I want to use a type-specific attribute? How should I go about this so that my code is nice and clean?

Do I just have one big if-elseif statement that I update every time I add a new type?

The code example below is Ruby on Rails, but the question applies to any language that supports polymorphism.

class Person < ActiveRecord::Base
  has_many :events
  has_many :meals, :through => :events, :source => :eventable,
    :source_type => "Meal"
  has_many :workouts, :through => :events, :source => :eventable,
    :source_type => "Workout"
end

Then I iter开发者_如何学运维ate:

p = Person.find(1)

p.eventable.each do |e|
  if e.meal?
    puts e.food_type
  elsif e.workout?
    puts e.repetitions
  elsif {...}
end

The above seems brittle. Is there a better way?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜