Introduction

*This is currently undergoing some rewrite. 2.x branch will introduce minor api incompatibilities.*

Peanuts is an library that allows for bidirectional mapping between Ruby objects and XML.

Released under the MIT license.

Features

  • Type awareness (extensible).

  • XML namespaces support.

  • Pluggable backends to work with different XML APIs (REXML implemented so far).

Installation

Stable branch 1.x available from Gemcutter

gem install peanuts --source http://gemcutter.org

Development branch 2.x available from Github. buggy/broken/missing docs

gem install omg-peanuts --source http://gems.github.com

Usage

Please see an example below. See also Peanuts, Peanuts::ClassMethods

TODO

  • Inheritance

  • Mixins

  • More mappings?

  • More types?

Docs

rdoc.info/projects/omg/peanuts

Bugs & such

Please report via Github issue tracking.

Example

class Cheezburger
  include Peanuts

  attribute :weight, :integer
end

class Cat
  include Peanuts

  namespaces :lol => 'urn:x-lol', :kthnx => 'urn:x-lol:kthnx'

  root 'kitteh', :xmlns => :lol

  attribute :has_tail, :boolean, :xmlname => 'has-tail', :xmlns => :kthnx
  attribute :ears, :integer

  element :ration, [:string], :xmlname => :eats, :xmlns => :kthnx
  element :name, :xmlns => 'urn:x-lol:kthnx'
  elements :paws, :xmlname => :paw

  element :friends, :xmlname => :pals do
    elements :names, :xmlname => :pal
  end

  element :cheezburger, Cheezburger
  element :moar_cheezburgers do
    elements :cheezburger, Cheezburger
  end
end

xml_fragment = <<-EOS
    <kitteh xmlns='urn:x-lol' xmlns:kthnx='urn:x-lol:kthnx' ears=' 2 ' kthnx:has-tail=' yes  '>
      <name xmlns='urn:x-lol:kthnx'>
          Silly
          Tom
      </name>
      <kthnx:eats>
        tigers
        lions
      </kthnx:eats>
      <pals>
        <pal>Chrissy</pal>
        <pal>Missy</pal>
        <pal>Sissy</pal>
      </pals>
      <paw>  one</paw>
      <paw> two </paw>
      <paw>three</paw>
      <paw>four</paw>
      <cheezburger weight='2' />
    </kitteh>
EOS
cat = Cat.restore_from(xml_fragment)

assert_equal 'Silly Tom', cat.name
assert_equal %w(tigers lions), cat.ration
assert_equal ['Chrissy', 'Missy', 'Sissy'], cat.friends.names
assert_equal 2, cat.ears
assert_equal true, cat.has_tail
assert_equal %w(one two three four), cat.paws
assert_kind_of Cheezburger, cat.cheezburger
assert_equal 2, cat.cheezburger.weight
...
puts cat.save_to(:string)

See also

Copyright © 2009 Igor Gunko, released under the MIT license