Class: Hoodoo::Presenters::Decimal

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

Overview

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



19
20
21
22
23
24
25
26
27
# File 'lib/hoodoo/presenters/types/decimal.rb', line 19

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.



12
13
14
# File 'lib/hoodoo/presenters/types/decimal.rb', line 12

def precision
  @precision
end

Instance Method Details

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

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



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/hoodoo/presenters/types/decimal.rb', line 31

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

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

  errors
end