Class: Hoodoo::Presenters::String

Inherits:
Field
  • Object
show all
Defined in:
lib/hoodoo/presenters/types/string.rb

Overview

A JSON String schema member.

Instance Attribute Summary collapse

Attributes inherited from Field

#default, #name, #required

Instance Method Summary collapse

Methods inherited from Field

#full_path, #has_default?, #render, #walk

Constructor Details

#initialize(name, options = {}) ⇒ String

Initialize a String instance with the appropriate name and options.

name

The JSON key.

options

A Hash of options, e.g. :required => true, :length => 10.



17
18
19
20
21
22
23
24
25
# File 'lib/hoodoo/presenters/types/string.rb', line 17

def initialize( name, options = {} )
  super( name, options )

  unless options.has_key?( :length )
    raise ArgumentError.new( 'Hoodoo::Presenters::String must have a :length' )
  end

  @length = options[ :length ]
end

Instance Attribute Details

#lengthObject

The maximum length of the String.



10
11
12
# File 'lib/hoodoo/presenters/types/string.rb', line 10

def length
  @length
end

Instance Method Details

#validate(data, path = '') ⇒ Object

Check if data is a valid String and return a Hoodoo::Errors instance.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hoodoo/presenters/types/string.rb', line 29

def validate( data, path = '' )
  errors = super( data, path )
  return errors if errors.has_errors? || ( ! @required && data.nil? )

  if data.is_a?( ::String )
    if data.size > @length
      errors.add_error(
        'generic.invalid_string',
        :message   => "Field `#{ full_path( path ) }` is longer than maximum length `#{ @length }`",
        :reference => { :field_name => full_path( path ) }
      )
    end
  else
    errors.add_error(
      'generic.invalid_string',
      :message   => "Field `#{ full_path( path ) }` is an invalid string",
      :reference => { :field_name => full_path( path ) }
    )
  end

  errors
end