M
Mariano Kamp
Hi,
given the following contrived example I am wondering how to use a
block with class_eval instead of using the string like in the code
below?!
Any ideas?
Cheers,
Mariano
require 'test/unit'
include Test::Unit::Assertions
class Base
class << self
def enhance(*attributes)
class_eval do
attr_reader *attributes
end
initializer = "def initialize(#{attributes.join(", ")})"
attributes.each {|a| initializer << "@#{a}=#{a}\n"}
initializer << "end"
# ------
class_eval initializer # <-------
# ------
end
end
end
class Derived < Base; end
Derived.enhancea, :b, :c)
d = Derived.new("a", "b", "c")
assert_equal "a", d.a
assert_equal "b", d.b
assert_equal "c", d.c
given the following contrived example I am wondering how to use a
block with class_eval instead of using the string like in the code
below?!
Any ideas?
Cheers,
Mariano
require 'test/unit'
include Test::Unit::Assertions
class Base
class << self
def enhance(*attributes)
class_eval do
attr_reader *attributes
end
initializer = "def initialize(#{attributes.join(", ")})"
attributes.each {|a| initializer << "@#{a}=#{a}\n"}
initializer << "end"
# ------
class_eval initializer # <-------
# ------
end
end
end
class Derived < Base; end
Derived.enhancea, :b, :c)
d = Derived.new("a", "b", "c")
assert_equal "a", d.a
assert_equal "b", d.b
assert_equal "c", d.c