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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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

  self.class.object_times.each do |field_name|
    ivar = "@#{field_name}"
    val  = instance_variable_get(ivar)
    time = Time.parse(val)
    instance_variable_set(ivar, time)
  end

  self.class.object_dates.each do |field_name|
    ivar = "@#{field_name}"
    val  = instance_variable_get(ivar)
    time = Date.parse(val)
    instance_variable_set(ivar, time)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



43
44
45
46
47
# File 'lib/xmlstats/object.rb', line 43

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

Class Method Details

.date(field_name) ⇒ Object



65
66
67
# File 'lib/xmlstats/object.rb', line 65

def self.date field_name
  object_dates << field_name
end

.object_datesObject



69
70
71
# File 'lib/xmlstats/object.rb', line 69

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

.object_referencesObject



53
54
55
# File 'lib/xmlstats/object.rb', line 53

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

.object_timesObject



61
62
63
# File 'lib/xmlstats/object.rb', line 61

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

.reference(field_name, field_type) ⇒ Object



49
50
51
# File 'lib/xmlstats/object.rb', line 49

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

.time(field_name) ⇒ Object



57
58
59
# File 'lib/xmlstats/object.rb', line 57

def self.time field_name
  object_times << field_name
end

Instance Method Details

#fieldsObject



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

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