Class: ActiveRecord::Bixformer::Attribute::Integer

Inherits:
Base
  • Object
show all
Defined in:
lib/activerecord-bixformer/attribute/integer.rb

Instance Attribute Summary

Attributes inherited from Base

#model, #name, #options

Instance Method Summary collapse

Methods inherited from Base

#export, #initialize, #should_be_included

Constructor Details

This class inherits a constructor from ActiveRecord::Bixformer::Attribute::Base

Instance Method Details

#import(value) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/activerecord-bixformer/attribute/integer.rb', line 5

def import(value)
  return nil if value.blank?

  unless value.strip.match(/\A[0-9]+\z/)
    if @options[:raise]
      raise ::ActiveRecord::Bixformer::AttributeError.new(self, value, :not_an_integer)
    else
      return nil
    end
  end

  numeric_value = value.to_i

  [
    [:greater_than,             -> (o, n) { n >  o }],
    [:greater_than_or_equal_to, -> (o, n) { n >= o }],
    [:less_than,                -> (o, n) { n <  o }],
    [:less_than_or_equal_to,    -> (o, n) { n <= o }],
  ].each do |restrict_name, validator|
    restrict_value = @options[restrict_name]

    next unless restrict_value.is_a?(::Integer)

    next if validator.call(restrict_value, numeric_value)

    if @options[:raise]
      raise ::ActiveRecord::Bixformer::AttributeError.new(self, value, restrict_name, count: restrict_value)
    else
      return nil
    end
  end

  numeric_value
end