Class: Hoodoo::Presenters::Decimal

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

Overview

A JSON Decimal schema member.

Constant Summary collapse

VALIDATOR =

In theory this is derived from Rubinius source, but “master” didn’t seem to include it at the time of writing. See:

github.com/rubinius/rubinius/ stackoverflow.com/questions/1034418/determine-if-a-string-is-a-valid-float-value

Regexp.new('^\s*[+-]?((\d+_?)*\d+(\.(\d+_?)*\d+)?|\.(\d+_?)*\d+)(\s*|([eE][+-]?(\d+_?)*\d+)\s*)$')

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

Initialize a Decimal instance with the appropriate name and options.

name

The JSON key.

options

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



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

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

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

  @precision = options[ :precision ]
end

Instance Attribute Details

#precisionObject

The precision of the Decimal.



20
21
22
# File 'lib/hoodoo/presenters/types/decimal.rb', line 20

def precision
  @precision
end

Instance Method Details

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

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

Decimals are expressed in JSON as Strings with any amount of leading or trailing space, can be positive or negative and may use simple (e.g. "-12.45") or scientific (e.g. "-0.1245e2") notation with a lower case or capital E in the latter case.

A leading “0” before a decimal place may be omitted; “0.12” and “.12” are considered equivalent and valid. An optional leading “+” is allowed for positive numbers. Between digits, an underscore is permitted as a visual separator; “12_431_999” and “12431999” are equivalent and valid.



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/hoodoo/presenters/types/decimal.rb', line 49

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

  unless data.is_a?( ::String ) && data.match( VALIDATOR ) != nil
    errors.add_error(
      'generic.invalid_decimal',
      :message   => "Field `#{ full_path( path ) }` is an invalid decimal",
      :reference => { :field_name => full_path( path ) }
    )
  end

  errors
end