Robert Klemme wrote:
> "Trans" <transfire / gmail.com> schrieb im Newsbeitrag
> news:1113449849.596475.60490 / z14g2000cwz.googlegroups.com...
> > 1) use a superclass rather than a module:
> >
> >  class MySuperClass
> >    def self.do_something
> >      puts "success"
> >    end
> >  end
> >
> >  class MyClass < MySuperClass
> >    do_something
> >  end
>
> Did you verify that this works?  :-)
>
> > 2) use extend instead of include:
> >
> >  module MyModule
> >    def do_something
> >      puts "success"
> >    end
> >  end
> >
> >  class MyClass
> >    extend MyModule
> >    do_something
> >  end
> >
> > 3) get tricky with it and use append_features:
> >
> >  module MyModule
> >    def self.append_features( aClass )
> >      def aClass.do_something
> >        puts "success"
> >      end
> >      super # must do this!
> >    end
> >  end
> >
> >  class MyClass
> >    include MyModule
> >    do_something
> >  end
> >
> > I do not recommend the later though.
>
> Here's what I do if I want to have a set of singleton methods
available for
> all classes in a class hierarchy:
>
> class Base
>   module MySpecialClassMethods
>     # make inheritance work:
>     def inherited(cl) cl.extend MySpecialClassMethods end
>
>     attr_accessor :bar
>     def foo() "foo" end
>     # other methods...
>   end
>
>   extend MySpecialClassMethods
> end
>
> class Derived < Base
> end
>
> >> Base.foo
> => "foo"
> >> Derived.foo
> => "foo"
>
> >> Base.bar = 1
> => 1
> >> Base.bar
> => 1
> >> Derived.bar
> => nil
> >> Derived.bar = 10
> => 10
> >> Derived.bar
> => 10
> >> Base.bar
> => 1
>
> The nice thing is that there is just one copy of those method
definitions
> plus you can change them or add new ones later and automatically all
classes
> in the hiearchy have them.
>
> Some background: you need to use the trick with #inherited() because
> singleton methods do not inherit along the class hierarchy because
the class
> of all classes is Class.
>
> >> Base.class
> => Class
> >> Derived.class
> => Class
> 
> Kind regards
> 
>     robert