Modules defining class methods to include?

irb(main):001:0> module Foo
irb(main):002:1> def foo
irb(main):003:2> "foo_instance"
irb(main):004:2> end
irb(main):005:1> def Foo.foo
irb(main):006:2> "foo_class"
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0> class Bar
irb(main):010:1> include Foo
irb(main):011:1> end
=> Bar
irb(main):012:0> Bar.new.foo
=> "foo_instance"
irb(main):013:0> Bar.foo
NoMethodError: undefined method `foo’ for Bar:Class
from (irb):13

How do I get Bar to “inherit” Foo.foo? I’ve done it before like this:

irb(main):001:0> module Foo
irb(main):002:1> def foo
irb(main):003:2> "foo_instance"
irb(main):004:2> end
irb(main):005:1> def Foo.included(aModule)
irb(main):006:2> super
irb(main):007:2> aModule.instance_eval do
irb(main):008:3* def foo
irb(main):009:4> "foo_class"
irb(main):010:4> end
irb(main):011:3> end
irb(main):012:2> end
irb(main):013:1> end
=> nil
irb(main):014:0> class Bar
irb(main):015:1> include Foo
irb(main):016:1> end
=> Bar
irb(main):017:0> Bar.new.foo
=> "foo_instance"
irb(main):018:0> Bar.foo
=> “foo_class”

But that’s rather ugly. Surely there’s a better way?

ruby 1.8.0 (2003-08-04) [i686-linux-gnu]

Tim.

···


Tim Bates
tim@bates.id.au

Tim Bates wrote:

How do I get Bar to “inherit” Foo.foo? I’ve done it before like this:

class Bar
include Foo
extend Foo
end

Joel VanderWerf wrote:

class Bar
include Foo
extend Foo
end

irb(main):017:0> Bar.new.foo
=> “foo_instance”
irb(main):018:0> Bar.foo
=> “foo_instance”

Not what I wanted.

···


Tim Bates
tim@bates.id.au

Tim Bates wrote:

Joel VanderWerf wrote:

class Bar
include Foo
extend Foo
end

irb(main):017:0> Bar.new.foo
=> “foo_instance”
irb(main):018:0> Bar.foo
=> “foo_instance”

Not what I wanted.

Oops. But you can do something like this:

module Foo
def foo
“foo_instance”
end
module Sub
def foo
“foo_class”
end
end
extend Sub # so Foo.foo still works
def Foo.included(aModule)
super
aModule.instance_eval do
extend Sub
end
end
end

class Bar
include Foo
end

p Bar.new.foo

p Bar.foo