Class: ChgkRating::Models::Base

Inherits:
ChgkObject show all
Includes:
Request
Defined in:
lib/chgk_rating/models/base.rb

Constant Summary

Constants included from Connection

Connection::BASE_URL

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Request

#get

Methods included from Connection

#connection

Methods inherited from ChgkObject

#build_model, #extract_id_from

Constructor Details

#initialize(id_or_hash, params = {}) ⇒ Base

Returns a new instance of Base.


13
14
15
16
17
18
19
20
21
# File 'lib/chgk_rating/models/base.rb', line 13

def initialize(id_or_hash, params = {})
  raw = raw_by id_or_hash, lazy_load?(params)

  # If we only have an ID and `lazy` is set to true, then simply store this ID
  # Otherwise extract all data from the hash
  raw.nil? ? @id = id_or_hash : extract_from(raw)

  @lazy = (params[:lazy] || false) unless self.class.const_defined?(:NO_LAZY_SUPPORT)
end

Instance Attribute Details

#lazyObject (readonly)

Returns the value of attribute lazy


6
7
8
# File 'lib/chgk_rating/models/base.rb', line 6

def lazy
  @lazy
end

Class Method Details

.inherited(subclass) ⇒ Object


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

def self.inherited(subclass)
  attr_reader(*subclass.attribute_mapping.keys) if subclass.attribute_mapping
  super
end

.no_eager_loading!Object


32
33
34
35
36
# File 'lib/chgk_rating/models/base.rb', line 32

def self.no_eager_loading!
  define_method :eager_load! do |*_args|
    raise ChgkRating::Error::EagerLoadingNotSupported
  end
end

.no_lazy_support!Object


38
39
40
41
# File 'lib/chgk_rating/models/base.rb', line 38

def self.no_lazy_support!
  self.const_set :NO_LAZY_SUPPORT, true
  undef_method :lazy
end

Instance Method Details

#eager_load!(force = false) ⇒ Object

Load data from API if the resource was initially lazily loaded. Set `force` to reload data even if it is already present.


25
26
27
28
29
30
# File 'lib/chgk_rating/models/base.rb', line 25

def eager_load!(force = false)
  return unless @lazy || force
  extract_from raw_by(self.id)
  @lazy = false
  self
end

#to_hObject


43
44
45
46
47
48
49
50
# File 'lib/chgk_rating/models/base.rb', line 43

def to_h
  self.class.attribute_mapping.inject({}) do |memo, (attr, mapping)|
    data = self.send attr
    data = mapping[:transform_down].call(data) if mapping.has_key?(:transform_down)
    memo[ mapping[:raw_name] ] = data
    memo
  end
end