Class: Rubee::Validatable::RuleChain

Inherits:
Object
  • Object
show all
Defined in:
lib/rubee/extensions/validatable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instance, attribute, state) ⇒ RuleChain

Returns a new instance of RuleChain.



27
28
29
30
31
32
# File 'lib/rubee/extensions/validatable.rb', line 27

def initialize(instance, attribute, state)
  @instance = instance
  @attribute = attribute
  @state = state
  @optional = false
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



25
26
27
# File 'lib/rubee/extensions/validatable.rb', line 25

def attribute
  @attribute
end

#instanceObject (readonly)

Returns the value of attribute instance.



25
26
27
# File 'lib/rubee/extensions/validatable.rb', line 25

def instance
  @instance
end

Instance Method Details

#condition(handler, error_message = nil) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rubee/extensions/validatable.rb', line 68

def condition(handler, error_message = nil)
  return self if @state.has_errors_for?(@attribute)
  value = @instance.send(@attribute)
  return self if @optional && value.nil?

  error_hash = assemble_error_hash(error_message, :condition)
  if handler.respond_to?(:call)
    @state.add_error(@attribute, error_hash) unless handler.call
  else
    @instance.send(handler)
  end

  self
end

#optionalObject



45
46
47
48
49
# File 'lib/rubee/extensions/validatable.rb', line 45

def optional(*)
  @optional = true

  self
end

#required(error_message = nil) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/rubee/extensions/validatable.rb', line 34

def required(error_message = nil)
  value = @instance.send(@attribute)

  error_hash = assemble_error_hash(error_message, :required, attribute: @attribute)
  if value.nil? || (value.respond_to?(:empty?) && value.empty?)
    @state.add_error(@attribute, error_hash)
  end

  self
end

#type(expected_class, error_message = nil) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rubee/extensions/validatable.rb', line 55

def type(expected_class, error_message = nil)
  return self if @state.has_errors_for?(@attribute)
  value = @instance.send(@attribute)
  return self if @optional && value.nil?

  error_hash = assemble_error_hash(error_message, :type, class: expected_class)
  unless value.is_a?(expected_class)
    @state.add_error(@attribute, error_hash)
  end

  self
end