Class: CORS::Rules
Overview
Internal class for handling rule definitions and validation.
Instance Method Summary collapse
-
#each ⇒ Hash<:name, :matcher, :required>, Enumerator
Yields each rule in order, or returns an Enumerator if no block was given.
-
#initialize {|self| ... } ⇒ Rules
constructor
A new instance of Rules.
-
#optional(*args, &block) ⇒ Hash
Same as #required, but the rule won’t run if the key is not present.
-
#required(name, constraints = nil) {|value| ... } ⇒ Hash
Declare a required rule; the value must be present, and it must match the given constraints or block matcher.
-
#validate(attributes) ⇒ Hash<name: [reason, rule]>
Validate a set of attributes against the defined rules.
Constructor Details
#initialize {|self| ... } ⇒ Rules
Returns a new instance of Rules.
16 17 18 19 |
# File 'lib/cors/rules.rb', line 16 def initialize @rules = [] yield self if block_given? end |
Instance Method Details
#each ⇒ Hash<:name, :matcher, :required>, Enumerator
Yields each rule in order, or returns an Enumerator if no block was given.
35 36 37 38 39 40 41 |
# File 'lib/cors/rules.rb', line 35 def each if block_given? @rules.each { |rule| yield rule } else @rules.enum_for(__method__) end end |
#optional(*args, &block) ⇒ Hash
Same as #required, but the rule won’t run if the key is not present.
87 88 89 |
# File 'lib/cors/rules.rb', line 87 def optional(*args, &block) required(*args, &block).tap { |rule| rule[:required] = false } end |
#required(name, constraints = nil) {|value| ... } ⇒ Hash
Declare a required rule; the value must be present, and it must match the given constraints or block matcher.
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/cors/rules.rb', line 65 def required(name, constraints = nil, &block) matcher = if block_given? then block elsif constraints.is_a?(Regexp) constraints.method(:===) elsif constraints.is_a?(String) constraints.method(:===) elsif constraints.is_a?(Array) constraints.method(:include?) else raise ArgumentError, "unknown matcher #{(constraints || block).inspect}" end { name: name, matcher: matcher, required: true }.tap do |rule| @rules << rule end end |
#validate(attributes) ⇒ Hash<name: [reason, rule]>
Validate a set of attributes against the defined rules.
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/cors/rules.rb', line 104 def validate(attributes) each_with_object({}) do |rule, failures| fail = lambda do |reason| failures[rule[:name]] = [reason, rule] end unless attributes.has_key?(rule[:name]) fail[:required] if rule[:required] next end unless rule[:matcher].call(attributes[rule[:name]]) fail[:match] end end end |