Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I dynamically update an instance array to hold a list of dynamic methods on instantiation?
    text
    copied!<p>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.</p> <p>My code looks something like this</p> <pre><code> 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 </code></pre> <p>So everything works except when I call xml_attributes on an instance it return null (and prints out 'xml_attrs = ').</p> <p>While the puts before the definition actually prints out the correct array. (when I instantiate the instance)</p> <p><hr> Update - <a href="https://stackoverflow.com/users/163203/kandadaboggu">kandadaboggu</a> solution below works. I really did not explain my question fully though so here is more information. I want to call xml_attr_reader within a class that extends XmlConfig. Basically I want it to work in the same way as attr_reader of active record.</p> <p>Taking <a href="https://stackoverflow.com/users/163203/kandadaboggu">kandadaboggu</a> solution of </p> <pre><code>class XmlConfig def xml_attr_reader(*args) args.each do |arg| class_eval(&lt;&lt;-RUBY, __FILE__, __LINE__) def #{arg} xml_mapping.#{arg} end RUBY end unless respond_to?(:xml_attributes) class_eval(&lt;&lt;-RUBY, __FILE__, __LINE__) attr_accessor :xml_attributes RUBY end (self.xml_attributes ||=[]).concat(args) end end </code></pre> <p>and</p> <pre><code>config = XmlConfig.new config.xml_attr_reader("age", "name") config.age #=&gt; age config.name #=&gt; name config.xml_attributes #=&gt; ["age", "name" ] config.xml_attr_reader("city") config.city #=&gt; city config.xml_attributes #=&gt; ["age", "name", "city"] </code></pre> <p>What I really want is this (where I had XmlConfig as a module not a Class in my version though)</p> <pre><code>class Event &lt; ActiveWhatever extend XmlConfig xml_attr_reader :age, :name xml_attr_reader :email, :location end class PrivateEvent &lt; Event xml_attr_reader :owner, :password end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload