A JSON Decimal schema member.

Methods
N
V
Constants
VALIDATOR =
Regexp.new('^\s*[+-]?((\d+_?)*\d+(\.(\d+_?)*\d+)?|\.(\d+_?)*\d+)(\s*|([eE][+-]?(\d+_?)*\d+)\s*)$')
 

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

Attributes
[RW] precision

The precision of the Decimal.

Class Public methods
new( name, options = {} )

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.

# 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 Public methods
validate( data, path = '' )

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.

# 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