V
Vincent L.
To build a wiki-like engine (or DSL) with dynamically generated
methods, I do the following :
class Base
def self.match(name, regexp, &block)
define_method(name) do |text|
text.gsub!(regexp) do
puts "$1 in match method : #{$1}"
#block.call
instance_eval(&block)
end
end
end
end
class Foo < Base
match :g, /(.)g$/i do
puts "$1 in passed block : #{$1}" #Unfortunately $1 is lost !
'ggg' #so only hardcoded values :-(
end
end
f = Foo.new
f.g('bla') #bla
f.g('doing') #doiggg ; problem is I cannot use $1 in block
After some research I found these 2 links
http://eigenclass.org/hiki/binding.of_caller+substitute
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/202600
(BTW I am trying to avoid any third-party libraries)
But I don't manage to get these to work...
I need to get $1, $2, etc. special values
in the block I pass in Base subclasses.
How can I do that ?
Thanks,
Vincent
methods, I do the following :
class Base
def self.match(name, regexp, &block)
define_method(name) do |text|
text.gsub!(regexp) do
puts "$1 in match method : #{$1}"
#block.call
instance_eval(&block)
end
end
end
end
class Foo < Base
match :g, /(.)g$/i do
puts "$1 in passed block : #{$1}" #Unfortunately $1 is lost !
'ggg' #so only hardcoded values :-(
end
end
f = Foo.new
f.g('bla') #bla
f.g('doing') #doiggg ; problem is I cannot use $1 in block
After some research I found these 2 links
http://eigenclass.org/hiki/binding.of_caller+substitute
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/202600
(BTW I am trying to avoid any third-party libraries)
But I don't manage to get these to work...
I need to get $1, $2, etc. special values
in the block I pass in Base subclasses.
How can I do that ?
Thanks,
Vincent