Class: LastFM::Struct
- Inherits:
-
Struct
- Object
- Struct
- LastFM::Struct
- 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.
Class Method Summary collapse
-
.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.
- .inherited(child) ⇒ Object
-
.package ⇒ String
Get the Last.fm package name for a Ruby class.
Instance Method Summary collapse
-
#initialize(h = {}) ⇒ Struct
constructor
Override Struct’s initialize method to accept a hash of members instead.
- #to_json(*a) ⇒ Object
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.
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 |
.package ⇒ String
Get the Last.fm package name for a Ruby class
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 |