Class: Rubee::Validatable::RuleChain
- Inherits:
-
Object
- Object
- Rubee::Validatable::RuleChain
- Defined in:
- lib/rubee/extensions/validatable.rb
Instance Attribute Summary collapse
-
#attribute ⇒ Object
readonly
Returns the value of attribute attribute.
-
#instance ⇒ Object
readonly
Returns the value of attribute instance.
Instance Method Summary collapse
- #condition(handler, error_message = nil) ⇒ Object
-
#initialize(instance, attribute, state) ⇒ RuleChain
constructor
A new instance of RuleChain.
- #optional ⇒ Object
- #required(error_message = nil) ⇒ Object
- #type(expected_class, error_message = nil) ⇒ Object
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
#attribute ⇒ Object (readonly)
Returns the value of attribute attribute.
25 26 27 |
# File 'lib/rubee/extensions/validatable.rb', line 25 def attribute @attribute end |
#instance ⇒ Object (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, = nil) return self if @state.has_errors_for?(@attribute) value = @instance.send(@attribute) return self if @optional && value.nil? error_hash = assemble_error_hash(, :condition) if handler.respond_to?(:call) @state.add_error(@attribute, error_hash) unless handler.call else @instance.send(handler) end self end |
#optional ⇒ Object
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( = nil) value = @instance.send(@attribute) error_hash = assemble_error_hash(, :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, = nil) return self if @state.has_errors_for?(@attribute) value = @instance.send(@attribute) return self if @optional && value.nil? error_hash = assemble_error_hash(, :type, class: expected_class) unless value.is_a?(expected_class) @state.add_error(@attribute, error_hash) end self end |