P
Pieter V.
I'm presently trying to work on a little metaprogramming project, but
am finding my efforts a little frustrated by ... well, I'm not rightly
sure what by. It seems to be a scoping issue, from what I can tell.
Here's a sample case:
############
class BlockTester
def x
"Correct Method!"
end
def self.x
"WRONG METHOD!"
end
def self.meth(name, &b)
# ... do some stuff
define_method name, &b
end
def self.normal_meth(name, &b)
meth(name, &b)
end
def self.special_meth(name, &b)
meth(name) do
# do something special
yield # <= This is the problematic call
end
end
end
# Test Case
class Foo < BlockTester
meth "foo" do x end
normal_meth "bar" do x end
special_meth "baz" do x end
end
f = Foo.new
f.foo # => "Correct Method!"
f.bar # => "Correct Method!"
f.baz # => "WRONG METHOD!"
############
The goal, as may not be immediately apparent from the code, is for
"special_meth" to be able to create a new method that automatically
executes a few lines of code before executing the block. While this
is similar in principle to overriding a method in a subclass...
############
class X
def to_s
"green" + super
end
end
############
... I can't seem to make this very common pattern stick for a block.
Any suggestions?
am finding my efforts a little frustrated by ... well, I'm not rightly
sure what by. It seems to be a scoping issue, from what I can tell.
Here's a sample case:
############
class BlockTester
def x
"Correct Method!"
end
def self.x
"WRONG METHOD!"
end
def self.meth(name, &b)
# ... do some stuff
define_method name, &b
end
def self.normal_meth(name, &b)
meth(name, &b)
end
def self.special_meth(name, &b)
meth(name) do
# do something special
yield # <= This is the problematic call
end
end
end
# Test Case
class Foo < BlockTester
meth "foo" do x end
normal_meth "bar" do x end
special_meth "baz" do x end
end
f = Foo.new
f.foo # => "Correct Method!"
f.bar # => "Correct Method!"
f.baz # => "WRONG METHOD!"
############
The goal, as may not be immediately apparent from the code, is for
"special_meth" to be able to create a new method that automatically
executes a few lines of code before executing the block. While this
is similar in principle to overriding a method in a subclass...
############
class X
def to_s
"green" + super
end
end
############
... I can't seem to make this very common pattern stick for a block.
Any suggestions?