Browse Source

Stat model

master
aeris 3 months ago
parent
commit
792bdf6d24
  1. 10
      app/models/stat.rb
  2. 11
      db/migrate/20220326181216_create_stats.rb
  3. 65
      spec/models/stat_spec.rb

10
app/models/stat.rb

@ -0,0 +1,10 @@
class Stat < ApplicationRecord
def self.create!(name, data, date = Date.today)
self.delete_by name: name, date: date
super name: name, date: date, data: data
end
def self.[](name)
self.where(name: name).order(date: :desc).limit(1).first
end
end

11
db/migrate/20220326181216_create_stats.rb

@ -0,0 +1,11 @@
class CreateStats < ActiveRecord::Migration[7.0]
def change
create_table :stats, id: :uuid do |t|
t.string :name
t.date :date
t.jsonb :data
end
add_index :stats, %i[name]
end
end

65
spec/models/stat_spec.rb

@ -0,0 +1,65 @@
require 'rails_helper'
describe Stat do
before do
Stat.delete_all
end
describe '#create!' do
it 'must create stats if not existing' do
name = 'foo'
today = Date.today
data = { 'bar' => 'baz' }
expect { Stat.create! name, data }
.to change { Stat.count }.from(0).to(1)
stat = Stat.first
expect(stat.name).to eq name
expect(stat.date).to eq today
expect(stat.data).to eq data
end
it 'must delete existing date if exist' do
name = 'foo'
today = Date.today
data = { 'bar' => 'baz' }
expect { Stat.create! name, data }
.to change { Stat.count }.from(0).to(1)
data = { 'bar' => 'qux' }
expect { Stat.create! name, data }
.to_not change { Stat.count }
stat = Stat.first
expect(stat.name).to eq name
expect(stat.date).to eq today
expect(stat.data).to eq data
end
end
describe '#[]' do
it 'must retrieve the youngest data' do
name = 'foo'
stat = Stat[name]
expect(stat).to be_nil
data = { 'bar' => 'baz' }
date = Date.new 1970, 1, 1
Stat.create! name, data, date
stat = Stat[name]
expect(stat).to_not be_nil
expect(stat.date).to eq date
expect(stat.data).to eq data
data = { 'bar' => 'qux' }
date = Date.new 1970, 1, 2
Stat.create! name, data, date
stat = Stat[name]
expect(stat).to_not be_nil
expect(stat.date).to eq date
expect(stat.data).to eq data
end
end
end
Loading…
Cancel
Save