Class: Validate::BlockParsingContext
- Inherits:
-
Object
- Object
- Validate::BlockParsingContext
- Defined in:
- lib/validate/parser.rb
Overview
The rules for parsing validations are such:
-
Validations are method calls (starting with the string ‘validates_`)
-
followed by field names as regular arguments (as symbols)
-
any options are included in an options hash, eg. is: String
-
and native blocks are reserved for children-validations
For example:
validates_subhash :iap1, :iap2, when: -> { type == :iap } do
validates_type_of :id, is: String
validates_type_of :tier, is: Numeric
end
Instance Attribute Summary collapse
-
#validations ⇒ Object
readonly
Returns the value of attribute validations.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize ⇒ BlockParsingContext
constructor
A new instance of BlockParsingContext.
- #method_missing(method, *args, &block) ⇒ Object
-
#run_when(condition, &block) ⇒ Object
‘when` is a special case, its syntax is as follows:.
Constructor Details
#initialize ⇒ BlockParsingContext
Returns a new instance of BlockParsingContext.
27 28 29 |
# File 'lib/validate/parser.rb', line 27 def initialize @validations = [] end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/validate/parser.rb', line 33 def method_missing(method, *args, &block) raise NoMethodError.new("No method #{method} to call in the context of a validation block.") unless method.to_s =~ /^validates/ raise NoMethodError.new("Undefined validation method: #{method}...") unless ValidationMethods.respond_to?(method) opts = args.pop if args.last.is_a?(::Hash) children = if block BlockParsingContext.parse(&block) end @validations << { name: method, fields: args, opts: opts, validations: children } end |
Instance Attribute Details
#validations ⇒ Object (readonly)
Returns the value of attribute validations.
31 32 33 |
# File 'lib/validate/parser.rb', line 31 def validations @validations end |
Class Method Details
.parse(&block) ⇒ Object
20 21 22 23 24 25 |
# File 'lib/validate/parser.rb', line 20 def self.parse(&block) # execute block, return array of validation methods called context = BlockParsingContext.new context.instance_exec(&block) context.validations end |
Instance Method Details
#run_when(condition, &block) ⇒ Object
‘when` is a special case, its syntax is as follows:
when -> { ... } do
# validations go here
end
54 55 56 57 58 59 60 61 62 |
# File 'lib/validate/parser.rb', line 54 def run_when(condition, &block) validations = BlockParsingContext.parse(&block) validations.map do |v| v[:opts] ||= {} v[:opts][:when] = condition v end @validations += validations end |