Class: ActiveAttr::Typecasting::BooleanTypecaster

Inherits:
Object
  • Object
show all
Defined in:
lib/active_attr/typecasting/boolean_typecaster.rb

Overview

Typecasts an Object to true or false

Examples:

Usage

BooleanTypecaster.new.call(1) #=> true

Since:

  • 0.5.0

Constant Summary collapse

FALSE_VALUES =

Values which force a false result for typecasting

These values are based on the YAML language.

Since:

  • 0.5.0

["n", "N", "no", "No", "NO", "false", "False", "FALSE", "off", "Off", "OFF", "f", "F"]
NIL_VALUES =

Values which force a nil result for typecasting

These values are based on the behavior of ActiveRecord

Since:

  • 0.14.0

["", nil]

Instance Method Summary collapse

Instance Method Details

#call(value) ⇒ true, false

Typecasts an object to true or false

Similar to ActiveRecord, when the attribute is a zero value or is a string that represents false, typecasting returns false. Otherwise typecasting just checks the presence of a value.

Examples:

Typecast an Integer

typecaster.call(1) #=> true

Parameters:

  • value (Object)

    The object to typecast

Returns:

  • (true, false)

    The result of typecasting

Since:

  • 0.5.0



41
42
43
44
45
46
47
48
# File 'lib/active_attr/typecasting/boolean_typecaster.rb', line 41

def call(value)
  case value
  when *FALSE_VALUES then false
  when *NIL_VALUES then nil
  when Numeric, /\A[-+]?(0++\.?0*|0*+\.?0+)\z/ then !value.to_f.zero?
  else value.present?
  end
end