Skip to content

Instantly share code, notes, and snippets.

@s4parke
Created June 29, 2017 19:17
Show Gist options
  • Save s4parke/91bfb839a1976bd9c4b42ca7b24ee0d0 to your computer and use it in GitHub Desktop.
Save s4parke/91bfb839a1976bd9c4b42ca7b24ee0d0 to your computer and use it in GitHub Desktop.
Typecast a value (string, integer, nil) to boolean using ActiveRecord(5.0)
## /config/initializers/cast_value_as_boolean.rb
##
## Typecast a value to boolean using ActiveRecord(5.0)
##
## 'whatever'.to_b => true
## 0.to_b => false
## Supported types:
# Integer
# String
# NilClass
# TrueClass
# FalseClass
## Truthy/Falsy values:
# truthy = [ true, 1, 'true', 'TRUE', '1', 'on', 'ON', 'whatever' ]
# falsy = [ false, 0, nil, '', 'false', 'FALSE', '0', 'off', 'OFF' ]
## Testing
# truthy.map(&:to_b)
# => [true, true, true, true, true, true, true, true]
# falsy.map(&:to_b)
# => [false, false, false, false, false, false, false, false, false]
class String
def to_b
if self.strip.length == 0
false
else
ActiveRecord::Type::Boolean.new.cast(self) # Rails 5
end
end
end
class Fixnum
def to_b
ActiveRecord::Type::Boolean.new.cast(self) # Rails 5
end
end
class NilClass
def to_b
false
end
end
class TrueClass
def to_b
true
end
end
class FalseClass
def to_b
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment