Class: XML::Node
- Inherits:
-
Object
- Object
- XML::Node
- Defined in:
- lib/libxml_additions.rb
Instance Method Summary collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/libxml_additions.rb', line 8 def method_missing( meth, *args ) # If one of the child nodes matches the string value of # the method call that triggered this method_missing(), # then why not use it? # # Furthermore, set an instance variable and create an # instance method so we don't have to come back here again. # # To avoid the collision of a node name with a built-in XML::Node # instance method (e.g., XML::Node#children would mask a <children> node), # you can refer to the node as [node]_in_the_xml # E.G., # n = XML::Node # n.children # => calls the XML::Node children instance method # n.children_in_the_xml # => looks for child nodes of n that happen to be named "children" node_name = meth.to_s =~ /^(.*)_in_the_xml$/ ? $1 : meth.to_s var_name = "@#{meth.to_s}_var" self.instance_eval( " def #{meth.to_s}(force=false) if force || #{var_name}.nil? #{var_name} = [] self.each_child { |c| #{var_name} << c if c.name == '#{node_name}' } #{var_name} = #{var_name}.first if #{var_name}.size == 1 end #{var_name} end", __FILE__, __LINE__ ) self.send( meth, *args ) end |