Class: Rbdash::Models::BaseModel

Inherits:
Object
  • Object
show all
Defined in:
lib/rbdash/models/base_model.rb

Direct Known Subclasses

Query

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(body) ⇒ BaseModel

Returns a new instance of BaseModel.



8
9
10
# File 'lib/rbdash/models/base_model.rb', line 8

def initialize(body)
  @body = body
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



6
7
8
# File 'lib/rbdash/models/base_model.rb', line 6

def body
  @body
end

Class Method Details

.clientObject



28
29
30
# File 'lib/rbdash/models/base_model.rb', line 28

def client
  Rbdash::Request.new
end

.find(id) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rbdash/models/base_model.rb', line 32

def find(id)
  response = client.get("#{endpoint}/#{id}")
  if response.code != 200
    puts response.code
    raise StandardError, 'abort!'
  end
  h = JSON.parse(response.body)
  body = h.select { |k, _| attributes.map(&:to_s).include?(k) }
  new(body)
end

.find_allObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rbdash/models/base_model.rb', line 43

def find_all
  all_results = []
  (1..100).each do |current_page|
    response = client.get(endpoint.to_s, params: { page: current_page })
    if response.code != 200
      puts response.code
      raise StandardError, 'abort!'
    end
    h = JSON.parse(response.body)
    results = h['results']
    all_results += results.map do |result|
      body = result.select { |k, _| attributes.map(&:to_s).include?(k) }
      new(body)
    end

    count = h['count']
    page = h['page']
    page_size = h['page_size']
    break if count <= page * page_size
  end
  all_results
end

.load(id) ⇒ Object

Raises:

  • (StandardError)


78
79
80
81
82
83
# File 'lib/rbdash/models/base_model.rb', line 78

def load(id)
  file = Dir.glob("#{dirname}/query-#{id}.json").first
  raise StandardError, 'id not found' unless file
  body = JSON.parse(File.read(file))
  new(body)
end

.update(id) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rbdash/models/base_model.rb', line 66

def update(id)
  request_body = load(id).body
  response = client.post("#{endpoint}/#{id}", body: request_body)
  if response.code != 200
    puts response.code
    puts response.headers
    puts response.body
    raise StandardError, 'abort!'
  end
  response
end

Instance Method Details

#saveObject



16
17
18
19
20
21
22
23
24
25
# File 'lib/rbdash/models/base_model.rb', line 16

def save
  id = @body['id']
  dirname = self.class.dirname
  Dir.mkdir(dirname) unless File.exist?(dirname)
  filename = "#{dirname}/query-#{id}.json"
  File.open(filename, 'w+') do |f|
    f.puts(to_json)
  end
  true
end

#to_jsonObject



12
13
14
# File 'lib/rbdash/models/base_model.rb', line 12

def to_json
  JSON.pretty_generate(body)
end