Modules defining class methods to include?

T

Tim Bates

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.
 
T

Tim Bates

Joel said:
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.
 
J

Joel VanderWerf

Tim said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,708
Latest member
SherleneF1

Latest Threads

Top