Class: TRuby::PredicateConstraint

Inherits:
Constraint show all
Defined in:
lib/t_ruby/constraint_checker.rb

Overview

Predicate constraint: Type where predicate_method

Instance Attribute Summary collapse

Attributes inherited from Constraint

#condition, #message, #type

Instance Method Summary collapse

Methods inherited from Constraint

#to_s

Constructor Details

#initialize(base_type:, predicate:) ⇒ PredicateConstraint

Returns a new instance of PredicateConstraint.



112
113
114
115
116
# File 'lib/t_ruby/constraint_checker.rb', line 112

def initialize(base_type:, predicate:)
  @base_type = base_type
  @predicate = predicate
  super(type: :predicate, condition: predicate.to_s)
end

Instance Attribute Details

#base_typeObject (readonly)

Returns the value of attribute base_type.



110
111
112
# File 'lib/t_ruby/constraint_checker.rb', line 110

def base_type
  @base_type
end

#predicateObject (readonly)

Returns the value of attribute predicate.



110
111
112
# File 'lib/t_ruby/constraint_checker.rb', line 110

def predicate
  @predicate
end

Instance Method Details

#satisfied?(value) ⇒ Boolean

Returns:

  • (Boolean)


118
119
120
121
122
123
124
125
126
# File 'lib/t_ruby/constraint_checker.rb', line 118

def satisfied?(value)
  if @predicate.is_a?(Proc)
    @predicate.call(value)
  elsif @predicate.is_a?(Symbol)
    value.respond_to?(@predicate) && value.send(@predicate)
  else
    false
  end
end

#validation_code(var_name) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/t_ruby/constraint_checker.rb', line 128

def validation_code(var_name)
  if @predicate.is_a?(Symbol)
    "#{var_name}.#{@predicate}"
  else
    "true" # Proc constraints require runtime evaluation
  end
end