Method: XML::Mapping.add_node_class

Defined in:
lib/xml/mapping/base.rb

.add_node_class(c) ⇒ Object

Registers the new node class c (must be a descendant of Node) with the xml-mapping framework.

A new “factory method” will automatically be added to ClassMethods (and therefore to all classes that include XML::Mapping from now on); so you can call it from the body of your mapping class definition in order to create nodes of type c. The name of the factory method is derived by “underscoring” the (unqualified) name of c; e.g. c==Foo::Bar::MyNiftyNode will result in the creation of a factory method named my_nifty_node. The generated factory method creates and returns a new instance of c. The list of argument to c.new consists of self (i.e. the mapping class the factory method was called from) followed by the arguments passed to the factory method. You should always use the factory methods to create instances of node classes; you should never need to call a node class’s constructor directly.

For a demonstration, see the calls to text_node, array_node etc. in the examples along with the corresponding node classes TextNode, ArrayNode etc. (these predefined node classes are in no way “special”; they’re added using add_node_class in mapping.rb just like any custom node classes would be).



505
506
507
508
509
510
511
512
# File 'lib/xml/mapping/base.rb', line 505

def self.add_node_class(c)
  meth_name = c.name.split('::')[-1].gsub(/^(.)/){$1.downcase}.gsub(/(.)([A-Z])/){$1+"_"+$2.downcase}
  ClassMethods.module_eval <<-EOS
    def #{meth_name}(*args)
      #{c.name}.new(self,*args)
    end
  EOS
end