How do I dynamically update an instance array to hold a list of dynamic methods on instantiation?
Posted
by Will
on Stack Overflow
See other posts from Stack Overflow
or by Will
Published on 2010-03-11T16:08:11Z
Indexed on
2010/03/11
21:49 UTC
Read the original article
Hit count: 219
ruby-on-rails
|ruby
I am trying to dynamically define methods based on xml mappings. This works really well. However I want to create an instance variable that is a array of the dynamically defined methods.
My code looks something like this
def xml_attr_reader(*args)
xml_list = ""
args.each do |arg|
string_val = "def #{arg}; " +
" xml_mapping.#{arg}; " +
"end; "
self.class_eval string_val
xml_hash = xml_list + "'#{arg}',"
end
self.class_eval "@xml_attributes = [] if @xml_attributes.nil?;" +
"@xml_attributes = @xml_attributes + [#{xml_list}];" +
"puts 'xml_attrs = ' + @xml_attributes.to_s;" +
"def xml_attributes;" +
" puts 'xml_attrs = ' + @xml_attributes.to_s;" +
" @xml_attributes;" +
"end"
end
So everything works except when I call xml_attributes on an instance it return null (and prints out 'xml_attrs = ').
While the puts before the definition actually prints out the correct array. (when I instantiate the instance)
© Stack Overflow or respective owner