Class: Hoodoo::Presenters::Enum

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

Overview

A JSON String schema member. An enumeration (of sorts) - a list of discrete string values that are permitted for the value of a field of this type. Matches must be exact (case sensitive, no leading/trailing white space etc.). Allowed values are expressed as Ruby strings or symbols (converted to and matched as strings) via an array under key :from in the options hash provided to the constructor.

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 = {}) ⇒ Enum

Initialize a String instance with the appropriate name and options.

name

The JSON key.

options

A Hash of options, e.g. :required => true, :from => [ :array, :of, :allowed, :enum, :values ].



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/hoodoo/presenters/types/enum.rb', line 25

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

  @from = options[ :from ]

  if @from.is_a?( ::Array )
    @from = @from.map { | entry | entry.to_s }
  else
    raise ArgumentError.new( 'Hoodoo::Presenters::Enum must have a :from array listing allowed values' )
  end
end

Instance Attribute Details

#fromObject

Array of permitted enumeration values. This may be written with non-String values but they will be converted to Strings when read back.



17
18
19
# File 'lib/hoodoo/presenters/types/enum.rb', line 17

def from
  @from
end

Instance Method Details

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

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/hoodoo/presenters/types/enum.rb', line 39

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

  unless @from.include?( data )
    errors.add_error(
      'generic.invalid_enum',
      :message   => "Field `#{ full_path( path ) }` does not contain an allowed reference value from this list: `#{@from}`",
      :reference => { :field_name => full_path( path ) }
    )
  end

  errors
end