Stat model

sites
aeris 2022-05-24 14:08:59 +02:00
parent 8d58fa62c2
commit 792bdf6d24
3 changed files with 86 additions and 0 deletions

10
app/models/stat.rb 100644
View File

@ -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

View File

@ -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

View File

@ -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