Class: Forecasting::Models::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/forecasting/models/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs, opts = {}) ⇒ Base

Returns a new instance of Base.



10
11
12
13
14
# File 'lib/forecasting/models/base.rb', line 10

def initialize(attrs, opts = {})
  @forecast_client = opts[:forecast_client] || Forecasting::Client.new(**opts)
  @attributes = attrs.dup
  @models = {}
end

Instance Attribute Details

#attributesHash

Returns:

  • (Hash)


8
9
10
# File 'lib/forecasting/models/base.rb', line 8

def attributes
  @attributes
end

#forecast_clientForecasting::Client (readonly)

Returns:



5
6
7
# File 'lib/forecasting/models/base.rb', line 5

def forecast_client
  @forecast_client
end

Class Method Details

.attributed(*attribute_names) ⇒ Object

Class method to define attribute methods for accessing attributes for a record

It needs to be used like this:

class User < ForecastRecord
  attributed :id,
             :title,
             :first_name
  ...
end

Parameters:

  • attribute_names (Array)

    A list of attributes



36
37
38
39
40
41
42
43
44
45
# File 'lib/forecasting/models/base.rb', line 36

def self.attributed(*attribute_names)
  attribute_names.each do |attribute_name|
    define_method(attribute_name) do
      @attributes[__method__.to_s]
    end
    define_method("#{attribute_name}=") do |value|
      @attributes[__method__.to_s.chop] = value
    end
  end
end

.modeled(opts = {}) ⇒ Object

Class method to define nested resources for a record.

It needs to be used like this:

class Project < Base
  modeled client: Client
  ...
end

Parameters:

  • opts (Hash) (defaults to: {})

    key = symbol that needs to be the same as the one returned by the Harvest API. value = model class for the nested resource.



57
58
59
60
61
62
63
64
# File 'lib/forecasting/models/base.rb', line 57

def self.modeled(opts = {})
  opts.each do |attribute_name, model|
    attribute_name_string = attribute_name.to_s
    define_method(attribute_name_string) do
      @models[attribute_name_string] ||= model.new(@attributes[attribute_name_string] || {}, forecast_client: forecast_client)
    end
  end
end

Instance Method Details

#to_hashHash

It returns keys and values for all the attributes of this record.

Returns:

  • (Hash)


19
20
21
# File 'lib/forecasting/models/base.rb', line 19

def to_hash
  @attributes
end