Class: Greeve::API::BaseItem

Inherits:
Object
  • Object
show all
Defined in:
lib/greeve/api/base_item.rb

Overview

An abstract class used to map XML responses from the EVE XML API into Ruby objects. This class is designed to be subclassed by classes representing the specific EVE API resources.

Direct Known Subclasses

CharacterInfo

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml_element) ⇒ BaseItem

Returns a new instance of BaseItem

Parameters:

  • xml_element (Ox::Element)

    the root XML element for this item

Raises:

  • (TypeError)


47
48
49
50
51
52
# File 'lib/greeve/api/base_item.rb', line 47

def initialize(xml_element)
  @xml_element = xml_element

  raise TypeError, "Cannot instantiate an abstract class" \
    if self.class.superclass != Greeve::API::BaseItem
end

Class Method Details

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

Map an XML attribute to a Ruby object.

Parameters:

  • name (Symbol)

    the Ruby name for this attribute

  • xpath (Hash)

    a customizable set of options

  • type (Hash)

    a customizable set of options

Returns:

  • the value located at the xpath



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/greeve/api/base_item.rb', line 18

def self.attribute(name, opts = {})
  name = name.to_sym
  @attributes ||= {}

  raise "Attribute `#{name}` defined more than once" if @attributes[name]
  raise "`:xpath` not specified for `#{name}`" unless opts[:xpath]

  @attributes[name] = {
    xpath: opts[:xpath],
    type: opts[:type],
  }

  define_method(name) do
    value = @xml_element.locate(opts[:xpath]).first

    case opts[:type]
    when :integer
      value.to_i
    when :numeric
      value.to_f
    when :string
      value.to_s
    else
      value
    end
  end
end

Instance Method Details

#inspectObject

:nodoc:



55
56
57
58
59
60
61
62
63
64
# File 'lib/greeve/api/base_item.rb', line 55

def inspect
  attrs = to_s

  unless attrs.empty?
    attrs = attrs.split("\n").map { |l| "  #{l}" }.join("\n")
    attrs = "\n#{attrs}\n"
  end

  "#<#{self.class.name}:#{object_id}#{attrs}>"
end

#to_sObject

:nodoc:



67
68
69
70
71
72
# File 'lib/greeve/api/base_item.rb', line 67

def to_s
  attrs =
    self.class.instance_variable_get(:@attributes)
      .map { |name, opts| "#{name}: #{__send__(name)}" }
      .join("\n")
end