From 1365f948db291fd63297076e0fd592211a532a43 Mon Sep 17 00:00:00 2001 From: Washington Botelho Date: Thu, 1 Mar 2018 17:49:51 -0300 Subject: [PATCH] feat: enable custom validation via yml config --- lib/rating/config.rb | 13 +++++++++++++ lib/rating/models/rating/rate.rb | 4 ++-- spec/config/validations_spec.rb | 27 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 spec/config/validations_spec.rb diff --git a/lib/rating/config.rb b/lib/rating/config.rb index facdefa..192008f 100644 --- a/lib/rating/config.rb +++ b/lib/rating/config.rb @@ -21,5 +21,18 @@ module Rating def rating_table @rating_table ||= config[__method__.to_s] || 'rating_ratings' end + + def validations + @validations ||= begin + default_scope = %w[author_type resource_id resource_type scopeable_id scopeable_type] + + { + rate: { + case_sensitive: config.dig('validations', 'rate', 'case_sensitive') || false, + scope: config.dig('validations', 'rate', 'scope') || default_scope + } + }.deep_stringify_keys + end + end end end diff --git a/lib/rating/models/rating/rate.rb b/lib/rating/models/rating/rate.rb index af365df..ec79e61 100644 --- a/lib/rating/models/rating/rate.rb +++ b/lib/rating/models/rating/rate.rb @@ -15,8 +15,8 @@ module Rating validates :value, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 100 } validates :author_id, uniqueness: { - case_sensitive: false, - scope: %i[author_type resource_id resource_type scopeable_id scopeable_type] + case_sensitive: ::Rating::Config.validations['rate']['case_sensitive'], + scope: ::Rating::Config.validations['rate']['scope'].map(&:to_sym) } def self.create(author:, extra_scopes:, metadata:, resource:, scopeable: nil, value:) diff --git a/spec/config/validations_spec.rb b/spec/config/validations_spec.rb new file mode 100644 index 0000000..0775f14 --- /dev/null +++ b/spec/config/validations_spec.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe Rating::Config, '.validations' do + context 'when rating.yml does not exist' do + it do + expect(subject.validations).to eq({ + rate: { + case_sensitive: false, + scope: %w[author_type resource_id resource_type scopeable_id scopeable_type] + } + }.deep_stringify_keys) + end + end if ENV['CONFIG_ENABLED_WITH_EXTRA_SCOPES'] != 'true' + + context 'when rating.yml exists' do + it do + expect(subject.validations).to eq({ + rate: { + case_sensitive: false, + scope: %w[author_type resource_id resource_type scopeable_id scopeable_type scope_1 scope_2] + } + }.deep_stringify_keys) + end + end if ENV['CONFIG_ENABLED_WITH_EXTRA_SCOPES'] == 'true' +end