Class: BlockScore::Base

Inherits:
Object
  • Object
show all
Extended by:
Connection
Defined in:
lib/blockscore/base.rb

Direct Known Subclasses

Candidate, Company, Person, QuestionSet, WatchlistHit

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Connection

delete, get, patch, post

Constructor Details

#initialize(options = {}, &block) ⇒ Base

Returns a new instance of Base.



7
8
9
10
11
# File 'lib/blockscore/base.rb', line 7

def initialize(options = {}, &block)
  @loaded = !(block)
  @proc = block
  @attributes = options
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/blockscore/base.rb', line 95

def method_missing(method, *args, &block)
  if respond_to_missing?(method)
    if setter?(method)
      add_setter(method, args)
    else
      add_accessor(method, args)
    end
    send(method, *args)
  else
    super
  end
end

Class Method Details

.api_urlObject



61
62
63
# File 'lib/blockscore/base.rb', line 61

def self.api_url
  'https://api.blockscore.com/'
end

.endpointObject



65
66
67
68
69
# File 'lib/blockscore/base.rb', line 65

def self.endpoint
  fail NotImplementedError, 'Base is an abstract class, not an API resource' if equal?(Base)

  "#{api_url}#{Util.to_plural(resource)}"
end

.resourceObject



57
58
59
# File 'lib/blockscore/base.rb', line 57

def self.resource
  @resource ||= Util.to_underscore(to_s.split('::').last)
end

Instance Method Details

#attributesObject



13
14
15
16
17
# File 'lib/blockscore/base.rb', line 13

def attributes
  return @attributes if @loaded
  force!
  @attributes
end

#force!Object



19
20
21
22
23
24
# File 'lib/blockscore/base.rb', line 19

def force!
  res = @proc.call
  @attributes = res.attributes.merge(@attributes)
  @loaded = true
  self
end

#idObject



26
27
28
# File 'lib/blockscore/base.rb', line 26

def id
  @attributes.fetch(:id, nil)
end

#inspectObject



30
31
32
33
# File 'lib/blockscore/base.rb', line 30

def inspect
  str_attr = "JSON:#{JSON.pretty_generate(attributes)}"
  "#<#{self.class}:0x#{object_id.to_s(16)} #{str_attr}>"
end

#persisted?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/blockscore/base.rb', line 71

def persisted?
  !id.nil?
end

#refreshObject



35
36
37
38
39
40
41
42
# File 'lib/blockscore/base.rb', line 35

def refresh
  res = self.class.retrieve(id)
  @attributes = res.attributes

  true
rescue Error
  false
end

#saveObject



44
45
46
47
48
# File 'lib/blockscore/base.rb', line 44

def save
  save!
rescue
  false
end

#save!Object



50
51
52
53
54
55
# File 'lib/blockscore/base.rb', line 50

def save!
  response = self.class.post(self.class.endpoint, attributes)
  @attributes = response.attributes

  true
end