Class instance method can't be defined in a module?

J

John Platte

Trying to work some attr_accessor - style magic so I can refactor a
bunch of menial methods into a single declaration. Can't subclass, so
I'm trying to do it with a module.

In the code below, I expect both of the "puts" lines to work on the
"abc" string, but I can't figure out what I'm missing. Can anyone
enlighten me here?

module FooModule
def delegate(*methods)
methods.each {|method|
module_eval %{
def #{method}
@new_receiver.#{method}
end
}
}
end
module_function :delegate
end

class TryIt
include FooModule
FooModule.delegate :intern
delegate :capitalize
def initialize(obj)
@new_receiver = obj
end
end

t = TryIt.new("abc")
puts t.intern
puts t.capitalize

=====
$ ruby demo.rb
demo.rb:17: undefined method `delegate' for TryIt:Class (NoMethodError)

(now comment out the line "delegate :capitalize")

$ ruby demo.rb
abc
demo.rb:25: undefined method `capitalize' for #<TryIt:0x283c8
@new_receiver="abc"> (NoMethodError)
 
M

Mauricio Fernández

Trying to work some attr_accessor - style magic so I can refactor a
bunch of menial methods into a single declaration. Can't subclass, so
I'm trying to do it with a module.

In the code below, I expect both of the "puts" lines to work on the
"abc" string, but I can't figure out what I'm missing. Can anyone
enlighten me here?

batsman@tux-chan:/tmp$ cat fdgdf.rb
module FooModule
def delegate(*methods)
methods.each do |method|
define_method(method){|*a| @new_receiver.send(method, *a) }
end
end
end

class TryIt
extend FooModule
delegate :intern
delegate :capitalize
def initialize(obj)
@new_receiver = obj
end
end

t = TryIt.new("abc")
puts t.intern
puts t.capitalize
batsman@tux-chan:/tmp$ ruby fdgdf.rb
abc
Abc

--
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

The documentation is in Japanese. Good luck.
-- Rich $alz
 
J

John Platte

extend FooModule

Thank you, Mauricio. This was indeed the fix I needed.

I guess I don't understand the distinction between "include" and
"extend" from the descriptions in the Pickaxe. There's apparently a
conceptual difference?
 
M

Mauricio Fernández

Thank you, Mauricio. This was indeed the fix I needed.

I guess I don't understand the distinction between "include" and
"extend" from the descriptions in the Pickaxe. There's apparently a
conceptual difference?

obj.extend Foo

works like

class << obj; include Foo end


--
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Linux is obsolete
-- Andrew Tanenbaum
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top