Class: Strelka::ParamValidator::RegexpConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/strelka/paramvalidator.rb

Overview

A constraint expressed as a regular expression.

Direct Known Subclasses

BuiltinConstraint

Constant Summary

Constants inherited from Constraint

Constraint::FLAGS, Constraint::TYPES

Instance Attribute Summary collapse

Attributes inherited from Constraint

#block, #description, #name

Instance Method Summary collapse

Methods inherited from Constraint

#==, #apply, for, #multiple?, register_type, #required?, #to_s

Methods included from MethodUtilities

#attr_predicate, #attr_predicate_accessor, #singleton_attr_accessor, #singleton_attr_reader, #singleton_attr_writer, #singleton_method_alias, #singleton_predicate_accessor, #singleton_predicate_reader

Constructor Details

#initialize(name, pattern, *args, &block) ⇒ RegexpConstraint

Create a new RegexpConstraint that will validate the field of the given name with the specified pattern.



254
255
256
257
258
# File 'lib/strelka/paramvalidator.rb', line 254

def initialize( name, pattern, *args, &block )
	@pattern = pattern

	super( name, *args, &block )
end

Instance Attribute Details

#patternObject (readonly)

The constraint's pattern



266
267
268
# File 'lib/strelka/paramvalidator.rb', line 266

def pattern
  @pattern
end

Instance Method Details

#check(value) ⇒ Object

Check the value against the regular expression and return its match groups if successful.



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/strelka/paramvalidator.rb', line 271

def check( value )
	self.log.debug "Validating %p via regexp %p" % [ value, self.pattern ]
	match = self.pattern.match( value.to_s ) or return nil

	if match.captures.empty?
		self.log.debug "  no captures, using whole match: %p" % [match[0]]
		return super( match[0] )

	elsif match.names.length > 1
		self.log.debug "  extracting hash of named captures: %p" % [ match.names ]
		rhash = self.matched_hash( match )
		return super( rhash )

	elsif match.captures.length == 1
		self.log.debug "  extracting one capture: %p" % [match.captures.first]
		return super( match.captures.first )

	else
		self.log.debug "  extracting multiple captures: %p" % [match.captures]
		values = match.captures
		return super( values )
	end
end

#matched_hash(match) ⇒ Object

Return a Hash of the given match object's named captures.



297
298
299
300
301
302
303
# File 'lib/strelka/paramvalidator.rb', line 297

def matched_hash( match )
	return match.names.inject( {} ) do |accum,name|
		value = match[ name ]
		accum[ name.to_sym ] = value
		accum
	end
end

#validator_descriptionObject

Return the constraint expressed as a String.



307
308
309
# File 'lib/strelka/paramvalidator.rb', line 307

def validator_description
	return "a value matching the pattern %p" % [ self.pattern ]
end