Module: Iora::Associations::HasMany

Includes:
Helpers
Included in:
Models::Element
Defined in:
lib/iora/associations/has_many.rb

Overview

The association HasMany defines a macro method for mapping a collection of XML elements to a Ruby method.

The macro is available to Element subclasses. For example:

class Award < Iora::Element; end

class Aquarium < Iora::Element
  has_many :fish, String
  has_many :awards, Award
end

aquarium = Aqarium.new(<<XML)
  <aquarium>
    <fish>Peter</specimen>
    <fish>Oswald</fish>
    <fish>Emma</fish>
    <recognition>
      <award name="Best Jellyfish"/>
      <award name="Nicest Shark"/>
    </recognition>
  </aquarium>
XML
aquarium.fish # => ['Peter', 'Oswald', 'Emma']
aquarium.awards # => [#<Award @element=...>, #<Award @element=...>]

Associations are inspired by Fullscreen/yt.

Instance Method Summary collapse

Methods included from Helpers

#parse_element, #tag_for

Instance Method Details

#has_many(name, klass, tag: tag_for(name).chomp('s')) ⇒ Object

Define a method to access a collection of XML element.

Parameters:

  • name (Symbol)

    the method name

  • klass (Class)

    the element class

  • tag (String) (defaults to: tag_for(name).chomp('s'))

    the element tag name


41
42
43
44
45
46
47
# File 'lib/iora/associations/has_many.rb', line 41

def has_many(name, klass, tag: tag_for(name).chomp('s'))
  define_method name do
    element.css(tag).map do |node|
      self.class.parse_element(node, klass)
    end.compact
  end
end