Hi,
I'm trying to implement a simple parser and quite likely going about it
the wrong way.
I would like to be able to include a bit of ruby code in a string, which
is saved to a field in a database. When the string is retrieve from the
database at a later stage, I want to parse it for code and evaluate the
code, substituting the result value into the string.
I've been trying to do something like this:
module Substitutable
@other_word = "other word"
proc = Proc.new{}
String.class_eval do
define_method :to_s do
self.gsub(/<code>(.*?)<\/code>/) do |match|
code = match.scan(/<code>(.*)<\/code>/).flatten.first
eval(code, proc.binding)
end
end
end
end
# If I then create a class and include Substitutable, I get the
following output
class Tester
include Substitutable
def say
@word = "hello"
'<code>@other_word</code>'.to_s # => "other word"
'<code>@word</code>'.to_s # => ""
'<code>"hard coded word"</code>'.to_s # => "hard coded word"
end
end
Tester.new.say
So I know that conceptually passing the a proc to the eval method does
enable me to set an instance variable out of the scope of the new to_s
method. But I cannot work out how to get the scope of the class within
which Substitutable has been "include"d. I've tried various things
like...
a) creating an "proc" method within the class that returns a proc object
b) creating a "@proc" instance variable within the class
...but with no luck.
Is what I'm trying to do possible?
Thanks very much in advance...
Dave
···
--
Posted via http://www.ruby-forum.com/.