C
Chris Olsen
I need to be able to create an object and, based on the param that I
pass in on the class create_for_sport method, create an object with the
proper module included.
It can be seen at the bottom by the comments I made that the includes
are being added on to the Stats class and the methods from the first
include are still there after the second include. Is there a way to add
an include to an object instance rather than a class?
Thanks for the help
########
module SoftballStats
def to_sport
puts "softball"
end
def batting_average
0.563
end
def before_save
puts "in the softball before save"
end
end
module HockeyStats
def to_sport
puts "hockey"
end
def scoring_percentage
0.34
end
def before_save
puts "in the hockey before save"
end
end
class Stats
def self.create_by_sport(sport)
s = Stats.new
s.sport = sport
return s
end
def sport=(sport)
Stats.instance_eval do # have tried to use self.instance_eval
eval("include #{sport.capitalize}Stats")
end
end
end
s = Stats.create_by_sport("softball")
puts s.batting_average # 0.563
h = Stats.create_by_sport("hockey")
puts h.scoring_percentage # 0.34
puts h.batting_average # 0.563 -> still has this method
s.before_save # "in the hockey save" -> softball before_save is now
overridden
h.before_save # "in the hockey save"
pass in on the class create_for_sport method, create an object with the
proper module included.
It can be seen at the bottom by the comments I made that the includes
are being added on to the Stats class and the methods from the first
include are still there after the second include. Is there a way to add
an include to an object instance rather than a class?
Thanks for the help
########
module SoftballStats
def to_sport
puts "softball"
end
def batting_average
0.563
end
def before_save
puts "in the softball before save"
end
end
module HockeyStats
def to_sport
puts "hockey"
end
def scoring_percentage
0.34
end
def before_save
puts "in the hockey before save"
end
end
class Stats
def self.create_by_sport(sport)
s = Stats.new
s.sport = sport
return s
end
def sport=(sport)
Stats.instance_eval do # have tried to use self.instance_eval
eval("include #{sport.capitalize}Stats")
end
end
end
s = Stats.create_by_sport("softball")
puts s.batting_average # 0.563
h = Stats.create_by_sport("hockey")
puts h.scoring_percentage # 0.34
puts h.batting_average # 0.563 -> still has this method
s.before_save # "in the hockey save" -> softball before_save is now
overridden
h.before_save # "in the hockey save"