Module: GoGoodreads::Attributes::ClassMethods

Defined in:
lib/go_goodreads/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, opts = {}) ⇒ Object

Parameters:

  • name (Symbol)

    the name of the attribute

  • opts (Hash) (defaults to: {})

    the options to configure the attribute

Options Hash (opts):

  • :type (Class)

    the class of the parsed value of the attribute

  • :using (Proc)

    a proc object to be used when finding the value in an xml node

  • :map_from (Symbol)

    a symbol where the value is placed when calling to_attributes!



14
15
16
17
18
19
20
21
# File 'lib/go_goodreads/attributes.rb', line 14

def attribute(name, opts = {})
  default_options = { :type => String, :map_from => name }
  setting = default_options.merge(opts)
  setting[:using] ||= lambda {|xml, from| (xml > from.to_s).text }
  @attributes ||= {}
  @attributes[name] = setting
  attr name
end

#Boolean(val) ⇒ Object



41
42
43
# File 'lib/go_goodreads/attributes.rb', line 41

def Boolean(val)
  {"true" => true, "false" => false}[val]
end

#to_attributes!(xml, options = {}) ⇒ Object

Parameters:

  • xml (Nokogiri::Node)

    the xml to be used in getting the attributes

  • options (Hash) (defaults to: {})

    settings for overriding default attribute configuration (key is the name of the attribute, value is the options hash)



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/go_goodreads/attributes.rb', line 25

def to_attributes!(xml, options = {})
  attrs = {}

  @attributes.each do |attr, config|
    opts = config.merge(options[attr] || {})
    map_from = opts[:map_from]
    callable = opts[:using]
    val = callable.call(xml, map_from)
    unless val.to_s.empty?
      attrs[attr] = _convert(val, opts[:type]) rescue val
    end
  end

  attrs
end