Skip to content

Commit

Permalink
fix: do not fail when case insentive enabled while having a complex c…
Browse files Browse the repository at this point in the history
…ontext object (#191)

* chore: return false when string operation is applied to non string context value
* Simplify and avoid modifying the context value (#192)
  • Loading branch information
gastonfournier committed Aug 29, 2024
1 parent 41bb877 commit d1da09b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
8 changes: 5 additions & 3 deletions lib/unleash/constraint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
8 changes: 7 additions & 1 deletion spec/unleash/constraint_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down

0 comments on commit d1da09b

Please sign in to comment.