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.



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

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.



107
108
109
# File 'lib/t_ruby/constraint_checker.rb', line 107

def base_type
  @base_type
end

#predicateObject (readonly)

Returns the value of attribute predicate.



107
108
109
# File 'lib/t_ruby/constraint_checker.rb', line 107

def predicate
  @predicate
end

Instance Method Details

#satisfied?(value) ⇒ Boolean

Returns:

  • (Boolean)


115
116
117
118
119
120
121
122
123
# File 'lib/t_ruby/constraint_checker.rb', line 115

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



125
126
127
128
129
130
131
# File 'lib/t_ruby/constraint_checker.rb', line 125

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