Module: Iora::Associations::HasAttribute

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

Overview

The association HasAttribute defines a macro method for mapping an XML attribute to a Ruby method.

The macro is available to Element subclasses. For example:

class Result < Iora::Element
  has_attribute :success?, Boolean
  has_attribute :response_time, Float, tag: 'timing'
end

result = Result.new("<result success="true" timing="2.668" />")
result.success? # => true
result.timing # => 2.668

Associations are inspired by Fullscreen/yt.

Instance Method Summary collapse

Methods included from Helpers

#parse_element, #tag_for

Instance Method Details

#has_attribute(name, klass = String, tag: tag_for(name), default: nil) ⇒ Object

Define a method to access an XML attribute.

Parameters:

  • name (Symbol)

    the method name

  • klass (Class) (defaults to: String)

    the class of the attribute

  • tag (String) (defaults to: tag_for(name))

    the attribute name

  • default (Object) (defaults to: nil)

    the default value


30
31
32
33
34
35
36
# File 'lib/iora/associations/has_attribute.rb', line 30

def has_attribute(name, klass = String, tag: tag_for(name), default: nil)
  define_method name do
    value = Coercer.coerce(element.attr(tag)).to(klass)
    return default if value.nil?
    value
  end
end