Class: GreenButtonData::Entry

Inherits:
Object
  • Object
show all
Includes:
Fetchable
Defined in:
lib/green-button-data/entry.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Fetchable

included

Constructor Details

#initialize(attributes) ⇒ Entry



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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/green-button-data/entry.rb', line 8

def initialize(attributes)
  # Automagically sets instance variables from attribute hash parsed from
  # the GreenButtonData::Parser classes
  attributes.each do |key, value|
    self.instance_variable_set :"@#{key}", value
  end

  # Handle relations via related_urls
  @related_urls.is_a?(Hash) and @related_urls.each do |key, value|
    self.instance_variable_set :"@#{key}_url", value
    singleton_class.class_eval do
      attr_accessor "#{key}_url".to_sym
    end

    # Define accessor methods from pluralized resource names
    self.class.send :define_method, "#{key.to_s.pluralize}" do |*args|
      id = args[0]
      options = args[1]

      klazz_name = "GreenButtonData::#{key.to_s.camelize}"

      # Handle deprecations
      klazz_name.gsub! /ElectricPowerUsageSummary/, 'UsageSummary'

      klazz = klazz_name.split('::')
                        .inject(Object) { |obj, cls| obj.const_get cls }

      collection = self.instance_variable_get "@#{key.to_s.pluralize}"
      url = self.instance_variable_get "@#{key}_url"

      # Make the ID argument optional
      options ||= if id.is_a?(Hash)
        id
      else
        {}
      end

      result = if id.is_a?(Numeric) || id.is_a?(String) || id.is_a?(Symbol)
        # Try returning cached results first
        collection and instance = collection.find_by_id(id)
        cache_miss = instance.nil?

        # On cache miss or forced reload, send API request
        instance = if !options[:reload] && instance
          instance
        else
          klazz.find "#{url}/#{id}", options
        end

        # Cache the result
        collection ||= ModelCollection.new
        collection << instance if cache_miss

        instance
      else
        if !options[:reload] && collection
          collection
        else
          collection = klazz.all url, options
        end
      end

      self.instance_variable_set :"@#{key.to_s.pluralize}", collection

      return result
    end
  end
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



5
6
7
# File 'lib/green-button-data/entry.rb', line 5

def id
  @id
end

#tokenObject

Returns the value of attribute token.



6
7
8
# File 'lib/green-button-data/entry.rb', line 6

def token
  @token
end