From b0738b5cc89ba1959c62894d2cd58e1aa0751f5c Mon Sep 17 00:00:00 2001 From: Washington Botelho Date: Fri, 26 Jan 2018 19:16:56 -0200 Subject: [PATCH] feat: add ability to persist metadata --- lib/rating/models/rating/rate.rb | 2 + spec/models/rate/create_spec.rb | 43 +++++++++++++++++++ .../add_comment_on_rating_rates_table.rb | 7 +++ 3 files changed, 52 insertions(+) create mode 100644 spec/support/db/migrate/add_comment_on_rating_rates_table.rb diff --git a/lib/rating/models/rating/rate.rb b/lib/rating/models/rating/rate.rb index 26f3966..877c35d 100644 --- a/lib/rating/models/rating/rate.rb +++ b/lib/rating/models/rating/rate.rb @@ -23,6 +23,8 @@ module Rating return record if record.persisted? && value == record.value + metadata.each { |k, v| record[k] = v } if metadata.present? + record.value = value record.save diff --git a/spec/models/rate/create_spec.rb b/spec/models/rate/create_spec.rb index fb319a3..9e3c684 100644 --- a/spec/models/rate/create_spec.rb +++ b/spec/models/rate/create_spec.rb @@ -128,4 +128,47 @@ RSpec.describe Rating::Rate, ':create' do end end end + + context 'with metadata' do + before { AddCommentOnRatingRatesTable.new.change } + + context 'with nil value' do + it 'creates a rate entry ignoring metadata' do + described_class.create author: author, metadata: nil, resource: article, value: 3 + + rate = described_class.last + + expect(rate.author).to eq author + expect(rate.comment).to eq nil + expect(rate.resource).to eq article + expect(rate.value).to eq 3 + end + end + + context 'with empty value' do + it 'creates a rate entry ignoring metadata' do + described_class.create author: author, metadata: '', resource: article, value: 3 + + rate = described_class.last + + expect(rate.author).to eq author + expect(rate.comment).to eq nil + expect(rate.resource).to eq article + expect(rate.value).to eq 3 + end + end + + context 'with hash value' do + it 'creates a rate entry with metadata included' do + described_class.create author: author, metadata: { comment: 'comment' }, resource: article, value: 3 + + rate = described_class.last + + expect(rate.author).to eq author + expect(rate.comment).to eq 'comment' + expect(rate.resource).to eq article + expect(rate.value).to eq 3 + end + end + end end diff --git a/spec/support/db/migrate/add_comment_on_rating_rates_table.rb b/spec/support/db/migrate/add_comment_on_rating_rates_table.rb new file mode 100644 index 0000000..690c213 --- /dev/null +++ b/spec/support/db/migrate/add_comment_on_rating_rates_table.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class AddCommentOnRatingRatesTable < ActiveRecord::Migration[5.0] + def change + add_column :rating_rates, :comment, :text + end +end