Robert Klemme
6/25/2005 3:31:00 PM
leon breedt <bitserf@gmail.com> wrote:
> Hi,
>
> I'm not exactly sure why defining a method with "def methodname"
> versus aliasing it would behave differently.
>
> My example code:
>
>
> ---< snip >---
>
> module O1
> def self.append_features(base)
> super
> base.extend(ClassMethods)
> base.class_eval do
> class << self
> alias_method :inherited_without_o1, :inherited
> alias_method :inherited, :inherited_with_o1
> end
> end
> puts "Including O1 into #{base.inspect}"
> end
>
> module ClassMethods
> def inherited_with_o1(child)
> puts "O1: BEFORE WITHOUT"
> inherited_without_o1(child)
> puts "O1: AFTER WITHOUT"
> puts "O1: #{child.inspect}"
> end
> end
> end
>
> module O2
> def self.append_features(base)
> super
> puts "Including O2 into #{base.inspect}"
> base.class_eval do
> class << self
> alias_method :inherited_without_o2, :inherited
> end
> end
> base.extend(ClassMethods)
> end
>
> module ClassMethods
> def inherited(child)
> puts "O2: BEFORE WITHOUT"
> inherited_without_o2(child)
> puts "O2: AFTER WITHOUT"
> puts "O2: #{child.inspect}"
> end
> end
> end
>
> class Override
> include O1
> include O2
> end
>
> class Child1 < Override
> end
>
> class Child2 < Child1
> end
>
> class Child3 < Override
> end
>
>
> ---< snip >---
>
> This prints:
>
>
> Including O1 into Override
> Including O2 into Override
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child1
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child2
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child3
>
>
> If I instead modify O2 to use the same approach as O1, I get the
> expected output:
>
>
> Including O1 into Override
> Including O2 into Override
> O2: BEFORE WITHOUT
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child1
> O2: AFTER WITHOUT
> O2: Child1
> O2: BEFORE WITHOUT
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child2
> O2: AFTER WITHOUT
> O2: Child2
> O2: BEFORE WITHOUT
> O1: BEFORE WITHOUT
> O1: AFTER WITHOUT
> O1: Child3
> O2: AFTER WITHOUT
> O2: Child3
>
>
>
> Why would using an alias to create the new "inherited" work, but a
> "def inherited" not?
>
>
> Help much appreciated..
> Leon
I guess it's this: the alias approach modifies method inherited of class
Override directly. But when you extend Override by O2, Override's inherited
shadows O2's inherited - so it's never called as there is no super call.
I'm not sure what exactly you want to achieve but maybe you are trying to do
more than necessary: if a class instance is extended by a module, sub class
instances inherit methods from the module automatically:
>> module Mod
>> def bar() "bar" end
>> end
=> nil
>> class Base
>> extend Mod
>> end
=> Base
>> Base.bar
=> "bar"
>> class Sub < Base
>> end
=> nil
>> Sub.bar
=> "bar"
Kind regards
robert