Trans
7/16/2008 3:50:00 AM
On Jul 15, 11:38=A0pm, Chris Olsen <olsen.ch...@gmail.com> wrote:
> 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. =A0Is there a way to ad=
d
> an include to an object instance rather than a class?
>
> Thanks for the help
>
> ########
> module SoftballStats
> =A0 def to_sport
> =A0 =A0 puts "softball"
> =A0 end
>
> =A0 def batting_average
> =A0 =A0 0.563
> =A0 end
>
> =A0 def before_save
> =A0 =A0 puts "in the softball before save"
> =A0 end
>
> end
>
> module HockeyStats
> =A0 def to_sport
> =A0 =A0 puts "hockey"
> =A0 end
>
> =A0 def scoring_percentage
> =A0 =A0 0.34
> =A0 end
>
> =A0 def before_save
> =A0 =A0 puts "in the hockey before save"
> =A0 end
>
> end
>
> class Stats
>
> =A0 def self.create_by_sport(sport)
> =A0 =A0 s =3D Stats.new
> =A0 =A0 s.sport =3D sport
> =A0 =A0 return s
> =A0 end
>
> =A0 def sport=3D(sport)
> =A0 =A0 Stats.instance_eval do =A0# have tried to use self.instance_eval
> =A0 =A0 =A0 eval("include #{sport.capitalize}Stats")
> =A0 =A0 end
> =A0 end
Couple of ways. One is to use the singleton.
def sport=3D(sport)
(class << self; self; end).class_eval %{
include #{sport.capitalize}Stats
}
end
But I think you might want to reconsider and use delegation instead.
T.