Class: Doggy::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/doggy/model.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = nil) ⇒ Model

Returns a new instance of Model.



174
175
176
177
178
179
180
181
182
# File 'lib/doggy/model.rb', line 174

def initialize(attributes = nil)
  root_key = self.class.root

  return super unless attributes && root_key
  return super unless attributes[root_key].is_a?(Hash)

  attributes = attributes[root_key]
  super(attributes)
end

Class Attribute Details

.rootObject

Returns the value of attribute root.



23
24
25
# File 'lib/doggy/model.rb', line 23

def root
  @root
end

Instance Attribute Details

#is_deletedObject

indicates whether an object locally deleted



17
18
19
# File 'lib/doggy/model.rb', line 17

def is_deleted
  @is_deleted
end

#loading_sourceObject

This stores whether the resource has been loaded locally or remotely.



20
21
22
# File 'lib/doggy/model.rb', line 20

def loading_source
  @loading_source
end

#pathObject

This stores the path on disk. We don’t define it as a model attribute so it doesn’t get serialized.



14
15
16
# File 'lib/doggy/model.rb', line 14

def path
  @path
end

Class Method Details

.accepted_response(code, accepted_errors = nil) ⇒ Object



123
124
125
126
127
128
129
# File 'lib/doggy/model.rb', line 123

def accepted_response(code, accepted_errors = nil)
  if (accepted_errors != nil) && (accepted_errors.include? code)
    true
  else
    code >= 200 && code < 400
  end
end

.all_local_resourcesObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/doggy/model.rb', line 46

def all_local_resources
  @@all_local_resources ||= Parallel.map(Dir[Doggy.object_root.join("**/*.json")]) do |file|
    raw = File.read(file, encoding: 'utf-8')
    begin
      attributes = JSON.parse(raw)
    rescue JSON::ParserError
      Doggy.ui.error "Could not parse #{ file }."
      next
    end
    resource = infer_type(attributes).new(attributes)
    resource.path = file
    resource.loading_source = :local
    resource
  end
end

.changed_resourcesObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/doggy/model.rb', line 62

def changed_resources
  repo = Rugged::Repository.new(Doggy.object_root.parent.to_s)
  diff = repo.diff(current_sha, 'HEAD')
  diff.find_similar!
  diff.each_delta.map do |delta|
    new_file_path = delta.new_file[:path]
    next unless new_file_path.match(/\Aobjects\//)
    is_deleted = delta.status == :deleted
    oid = is_deleted ? delta.old_file[:oid] : delta.new_file[:oid]
    begin
      attributes = JSON.parse(repo.read(oid).data)
    rescue JSON::ParserError
      Doggy.ui.error("Could not parse #{ new_file_path }. Skipping...")
      next
    end
    resource = infer_type(attributes).new(attributes)
    resource.loading_source = :local
    resource.path = Doggy.object_root.parent.join(new_file_path).to_s
    resource.is_deleted = is_deleted
    resource
  end.compact
end

.current_shaObject



131
132
133
134
135
136
# File 'lib/doggy/model.rb', line 131

def current_sha
  now = Time.now.to_i
  month_ago = now - 3600 * 24 * 30
  result = request(:get, "https://app.datadoghq.com/api/v1/events?start=#{ month_ago }&end=#{ now }&tags=audit,shipit")
  result['events'][0]['text'] # most recetly deployed SHA
end

.emit_shipit_deploymentObject



138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/doggy/model.rb', line 138

def emit_shipit_deployment
  return unless ENV['SHIPIT']

  request(:post, 'https://app.datadoghq.com/api/v1/events', {
    title: "ShipIt Deployment by #{ENV['USER']}",
    text: ENV['REVISION'],
    tags: %w(audit shipit),
    date_happened: Time.now.to_i,
    priority: 'normal',
    source_type_name: 'shipit'
  }.to_json)
end

.find(id) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/doggy/model.rb', line 25

def find(id)
  attributes = request(:get, resource_url(id), nil, [404])
  return if attributes['errors']
  resource   = new(attributes)

  resource.loading_source = :remote
  resource
end

.find_local(param) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/doggy/model.rb', line 34

def find_local(param)
  resources  = Doggy::Model.all_local_resources
  if (id = param).is_a?(Integer) || (param =~ /^[0-9]+$/ && id = Integer(param)) then
    return resources.find { |res| res.id == id }
  end
  if id = param[/(dash\/|screen\/|monitors#)(\d+)/i, 2]
    return resources.find { |res| res.id == Integer(id) }
  end
  full_path = File.expand_path(param.gsub('objects/', ''), Doggy.object_root)
  resources.find { |res| res.path == full_path }
end

.infer_type(attributes) ⇒ Object



85
86
87
88
89
90
# File 'lib/doggy/model.rb', line 85

def infer_type(attributes)
  has_key = ->(key) { attributes.has_key?(key.to_s) || attributes.has_key?(key.to_sym) }
  return Models::Dashboard if has_key.call('graphs')
  return Models::Monitor   if has_key.call('message')
  return Models::Screen    if has_key.call('board_title')
end

.request(method, url, body = nil, accepted_errors = nil) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/doggy/model.rb', line 92

def request(method, url, body = nil, accepted_errors = nil)
  uri = URI(url)

  if uri.query
    uri.query = "api_key=#{ Doggy.api_key }&application_key=#{ Doggy.application_key }" + '&' + uri.query
  else
    uri.query = "api_key=#{ Doggy.api_key }&application_key=#{ Doggy.application_key }"
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')

  request = case method
            when :get    then Net::HTTP::Get.new(uri.request_uri)
            when :post   then Net::HTTP::Post.new(uri.request_uri)
            when :put    then Net::HTTP::Put.new(uri.request_uri)
            when :delete then Net::HTTP::Delete.new(uri.request_uri)
            end

  request.content_type = 'application/json'
  request.body = body if body

  response = http.request(request)
  parsed_response = response.body ? JSON.parse(response.body) : nil

  unless accepted_response(response.code.to_i, accepted_errors)
    raise DoggyError, "Unexpected response code #{response.code} for #{url}, body: #{parsed_response.to_s}"
  end
  parsed_response
end

.sort_by_key(hash, &block) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
# File 'lib/doggy/model.rb', line 151

def sort_by_key(hash, &block)
  hash.keys.sort(&block).reduce({}) do |seed, key|
    seed[key] = hash[key]
    if seed[key].is_a?(Hash)
      seed[key] = Doggy::Model.sort_by_key(seed[key], &block)
    elsif seed[key].is_a?(Array)
      seed[key].each_with_index { |e, i| seed[key][i] = sort_by_key(e, &block) if e.is_a?(Hash) }
    end
    seed
  end
end

Instance Method Details

#==(another_model) ⇒ Object

class << self



170
171
172
# File 'lib/doggy/model.rb', line 170

def ==(another_model)
  to_h == another_model.to_h
end

#destroyObject



214
215
216
# File 'lib/doggy/model.rb', line 214

def destroy
  request(:delete, resource_url(id))
end

#destroy_localObject



218
219
220
# File 'lib/doggy/model.rb', line 218

def destroy_local
  File.delete(@path)
end

#saveObject



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/doggy/model.rb', line 198

def save
  ensure_managed_emoji!
  validate

  body = JSON.dump(to_h)
  if !id then
    attributes = request(:post, resource_url, body)
    self.id    = self.class.new(attributes).id
    save_local
    Doggy.ui.say "Created #{ path }"
  else
    request(:put, resource_url(id), body)
    Doggy.ui.say "Updated #{ path }"
  end
end

#save_localObject



184
185
186
187
188
# File 'lib/doggy/model.rb', line 184

def save_local
  ensure_read_only!
  self.path ||= Doggy.object_root.join("#{prefix}-#{id}.json")
  File.open(@path, 'w') { |f| f.write(JSON.pretty_generate(to_h)) }
end

#to_hObject



190
191
192
# File 'lib/doggy/model.rb', line 190

def to_h
  Doggy::Model.sort_by_key(super)
end

#validateObject



194
195
196
# File 'lib/doggy/model.rb', line 194

def validate
  # NotImplemented
end