Class: Kharon::Processors::NumericProcessor

Inherits:
Kharon::Processor show all
Defined in:
lib/kharon/processors/numeric_processor.rb

Overview

Processor to validate integers. It has the :between, :round, :floor, :ceil, :min, and :max options with the default ones.

Author:

Instance Attribute Summary

Attributes inherited from Kharon::Processor

#validator

Instance Method Summary (collapse)

Methods inherited from Kharon::Processor

#initialize

Constructor Details

This class inherits a constructor from Kharon::Processor

Instance Method Details

- (Object) process(key, options = {})

Checks if the given key is an integer or not.

Examples:

Validates a key so it has to be an integer superior or equal to 2.

@validator.integer(:an_integer_key, min: 2)

Parameters:

  • key (Object)

    the key about which verify the type.

  • options (Hash) (defaults to: {})

    a hash of options passed to this method (see documentation to know which options pass).



15
16
17
18
# File 'lib/kharon/processors/numeric_processor.rb', line 15

def process(key, options = {})
  before_all(key, options)
  match?(key, /\A([+-]?\d+)([,.](\d+))?\Z/) ? store(key, ->(item){item.to_s.sub(/,/, ".").to_f}, options) : raise_type_error(key, "Numeric")
end

- (Object) store(key, process, options)

Stores a decimal number, then apply the eventually passed round, ceil, or floor options.

Parameters:

  • key (Object)

    the key associated with the value to store in the filtered datas.

  • process (Proc)

    a process (lambda) to execute on the initial value. Must contain strictly one argument.

  • options (Hash)

    the options applied to the initial value.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/kharon/processors/numeric_processor.rb', line 24

def store(key, process, options)
  if(options.has_key?(:between))
    check_min_value(key, options[:between][0])
    check_max_value(key, options[:between][1])
  else
    check_min_value(key, options[:min]) if(options.has_key?(:min))
    check_max_value(key, options[:max]) if(options.has_key?(:max))
  end
  super(key, process, options)
  if options.has_key?(:round)
    if options[:round].kind_of?(Integer)
      validator.filtered[key] = validator.filtered[key].round(options[:round]) if validator.filtered.has_key?(key)
    elsif options[:round] == true
      validator.filtered[key] = validator.filtered[key].round if validator.filtered.has_key?(key)
    end
  elsif(options.has_key?(:floor) and options[:floor] == true)
    validator.filtered[key] = validator.filtered[key].floor if validator.filtered.has_key?(key)
  elsif(options.has_key?(:ceil) and options[:ceil] == true)
    validator.filtered[key] = validator.filtered[key].ceil if validator.filtered.has_key?(key)
  end
end