Class: Xmlstats::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/xmlstats/object.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Object

Returns a new instance of Object.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/xmlstats/object.rb', line 5

def initialize params = {}
  params.each do |key, value|
    instance_variable_set "@#{key}", value
  end

  self.class.object_references.each do |field_name, field_type|
    ivar = "@#{field_name}"
    val  = instance_variable_get(ivar)

    # Turn hashes into objects, turn arrays into arrays of objects.
    obj =
      case val
      when Array then val.map { |v| field_type.new v }
      else            field_type.new val
      end

    instance_variable_set ivar, obj
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



29
30
31
32
33
# File 'lib/xmlstats/object.rb', line 29

def method_missing name, *args, &block
  ivar = instance_variable_get("@#{name}")
  return ivar if ivar
  super
end

Class Method Details

.object_referencesObject



40
41
42
# File 'lib/xmlstats/object.rb', line 40

def self.object_references
  @object_references ||= []
end

.reference(field_name, field_type) ⇒ Object



35
36
37
38
# File 'lib/xmlstats/object.rb', line 35

def self.reference field_name, field_type
  @object_references ||= []
  @object_references << [ field_name, field_type ]
end

Instance Method Details

#fieldsObject



25
26
27
# File 'lib/xmlstats/object.rb', line 25

def fields
  instance_variables.map(&:to_s).map { |s| s.gsub(/^@/, "").to_sym }
end