defining a method relative to a module's nesting

T

Trans

module X
def self.included(mod)
define_method ... # define method from here
end
end

module N
# <- define method to this namespace (N)
module M
include X
end
end

T.
 
A

Ara.T.Howard

module X
def self.included(mod)
define_method ... # define method from here
end
end

module N
# <- define method to this namespace (N)
module M
include X
end
end

T.

one way:

harp:~ > cat a.rb
module X
def self::included other
class << other
eval <<-code
def foo
42
end
code
end
super
end
end

module N
module M
include X
end
end

p N::M::foo

harp:~ > ruby a.rb
42


nicer way:

harp:~ > cat a.rb
module X
module ClassMethods
def foo
42
end
end
module InstanceMethods
def foo
'forty-two'
end
end
def self::included other
other.module_eval{
extend ClassMethods
include InstanceMethods
}
end
end

class N
class M
include X
end
end

p N::M::foo

nm = N::M::new
p nm.foo

harp:~ > ruby a.rb
42
"forty-two"


kind regards.

-a
--
===============================================================================
| email :: ara [dot] t [dot] howard [at] noaa [dot] gov
| phone :: 303.497.6469
| Your life dwells amoung the causes of death
| Like a lamp standing in a strong breeze. --Nagarjuna
===============================================================================
 
M

Mauricio Fernández

module X
def self.included(mod)
define_method ... # define method from here
end
end

module N
# <- define method to this namespace (N)
module M
include X
end
end

batsman@tux-chan:~/src/ruby/ruby.head$ cat /tmp/fgdsdgdfg.rb
module X
def self.included(mod)
# for top-level module, parent = self; change for other semantics
parent = Object.const_get(mod.to_s.sub(/::[^:]+\z/, ""))
parent.send:)define_method, :foo){ puts "#{parent.to_s}#foo" } #fcall in 1.9
class << parent; self end.send:)define_method, :bar) do #fcall in 1.9
puts "#{parent.to_s}.bar"
end
end
end

module M
module N
include X
end
end

Class.new{ include M }.new.foo
M.bar
batsman@tux-chan:~/src/ruby/ruby.head$ ruby /tmp/fgdsdgdfg.rb
M#foo
M.bar
 
T

Trans

Mauricio,

That did the trick! Me thinks I will be generalizing the whole

parent = Object.const_get(mod.to_s.sub(/::[^:]+\z/, ""))

thing in Nano.

Thanks,
T.
 
T

Trans

class Module

def nesting
n = []
name.split(/::/).inject(self){ |mod, name| c = mod.const_get(name)
; n << c ; c }
return n
end

end
 
T

Trans

Oh,

I really hope not --an odd named meta-programming method. Please, I
beg, use #instance_send.

T.
 

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,776
Messages
2,569,602
Members
45,183
Latest member
OrderGlycoEase

Latest Threads

Top