From d1da09bc5b742d3ea4bb8e99d7d5f1b1da87cd17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gast=C3=B3n=20Fournier?= Date: Thu, 29 Aug 2024 12:04:47 +0200 Subject: [PATCH] fix: do not fail when case insentive enabled while having a complex context object (#191) * chore: return false when string operation is applied to non string context value * Simplify and avoid modifying the context value (#192) --- lib/unleash/constraint.rb | 8 +++++--- spec/unleash/constraint_spec.rb | 8 +++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/unleash/constraint.rb b/lib/unleash/constraint.rb index 104c7ef..26a59b2 100644 --- a/lib/unleash/constraint.rb +++ b/lib/unleash/constraint.rb @@ -22,6 +22,8 @@ class Constraint FALLBACK_VALIDATOR: ->(_context_v, _constraint_v){ false } }.freeze + STRING_OPERATORS = [:STR_STARTS_WITH, :STR_ENDS_WITH, :STR_CONTAINS].freeze + LIST_OPERATORS = [:IN, :NOT_IN, :STR_STARTS_WITH, :STR_ENDS_WITH, :STR_CONTAINS].freeze def initialize(context_name, operator, value = [], inverted: false, case_insensitive: false) @@ -106,10 +108,10 @@ def matches_constraint?(context) v = self.value.dup context_value = context.get_by_name(self.context_name) - v.map!(&:upcase) if self.case_insensitive - context_value = context_value.upcase if self.case_insensitive + # always return false, if we are comparing a non string with a string operator: + return false if !context_value.is_a?(String) && STRING_OPERATORS.include?(self.operator) - OPERATORS[self.operator].call(context_value, v) + OPERATORS[self.operator].call(*self.case_insensitive ? [context_value.upcase, v.map(&:upcase)] : [context_value, v]) end end end diff --git a/spec/unleash/constraint_spec.rb b/spec/unleash/constraint_spec.rb index 9fd4b9b..879a1d1 100644 --- a/spec/unleash/constraint_spec.rb +++ b/spec/unleash/constraint_spec.rb @@ -370,7 +370,10 @@ session_id: 'verylongsesssionid', remote_address: '127.0.0.1', properties: { - env: 'development' + env: 'development', + complex: { + type: 'development' + } } } context = Unleash::Context.new(context_params) @@ -382,6 +385,9 @@ constraint = Unleash::Constraint.new('env', 'STR_CONTAINS', ['LOP'], case_insensitive: true) expect(constraint.matches_context?(context)).to be true + + constraint = Unleash::Constraint.new('complex', 'STR_CONTAINS', ['development'], case_insensitive: true) + expect(constraint.matches_context?(context)).to be false end it 'matches based on case insensitive property when context is uppercased' do