Class: LastFM::Struct

Inherits:
Struct
  • Object
show all
Defined in:
lib/lastfm/struct.rb

Overview

Prodives modifications to Ruby's Struct class for use within the LastFM module space. Must be called 'Struct' to play nice with YARD's @attr documentation.

Direct Known Subclasses

Album, Artist, Buylink, Event, Shout, Tag, Track, Venue, Wiki

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(h = {}) ⇒ Struct

Override Struct's initialize method to accept a hash of members instead.


22
23
24
# File 'lib/lastfm/struct.rb', line 22

def initialize(h={})
  members.each{|m| self[m] = h[m.to_sym]}
end

Class Method Details

.from_xml(xml, initial_attributes = {}) ⇒ LastFM::Struct

Construct a LastFM::Struct object from XML, using each inheritor's attr_from_node method to determine how to manipulate individual attributes.

Parameters:

  • xml (LibXML::XML::Document)

    XML obtained from a Last.fm API call

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

    Attributes to set before parsing the XML

Returns:

  • (LastFM::Struct)

    object contructed from attributes contained in XML


39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/lastfm/struct.rb', line 39

def self.from_xml(xml, initial_attributes={})
  xml = xml.find_first(self.package) if xml.is_a?(LibXML::XML::Document)
  model = self.new(initial_attributes)
  xml.find('*').each{|node|
    if self.method_defined?(:update_from_node)
      model.update_from_node(node)
    else
      model.send(:"#{node.name}=", node)
    end
  }
  model
end

.inherited(child) ⇒ Object


7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/lastfm/struct.rb', line 7

def self.inherited(child)
  child.class_eval do
    members.each do |mem|
      # Override member= methods to filter through parse_node when given an XML::Node
      define_method(:"#{mem}=") do |val|
        val = parse_node(mem, val) if val.is_a?(LibXML::XML::Node)
        super val
      end
    end if public_methods.include?(:members)
  end

  super
end

.packageString

Get the Last.fm package name for a Ruby class

Returns:

  • (String)

    the Last.fm package name


29
30
31
# File 'lib/lastfm/struct.rb', line 29

def self.package
  self.to_s.downcase.split('::').last
end

Instance Method Details

#to_json(*a) ⇒ Object


52
53
54
55
56
# File 'lib/lastfm/struct.rb', line 52

def to_json(*a)
  members.inject({}){|map, m|
    map[m] = self[m]; map
  }.to_json(*a)
end