Last active
June 11, 2020 08:22
-
-
Save attenzione/a7ffe04ca28c57ffaa14 to your computer and use it in GitHub Desktop.
Ruby: casting to boolean value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BooleanValue | |
# https://github.com/rails/rails/blob/master/activemodel/lib/active_model/type/boolean.rb | |
FALSE_VALUES = [ | |
false, 0, | |
"0", :"0", | |
"f", :f, | |
"F", :F, | |
"false", :false, | |
"FALSE", :FALSE, | |
"off", :off, | |
"OFF", :OFF, | |
].to_set.freeze | |
class << self | |
def cast(value) | |
Rails.present? ? with_rails(value) : without_rails(value) | |
end | |
private | |
def with_rails(value) | |
major, minor, _patch = Rails.version.split('.').map(&:to_i) | |
case major | |
# Rails 5 | |
when 5, 6 | |
ActiveRecord::Type::Boolean.new.cast(value) | |
# Rails 4 | |
when 4 | |
# Rails < 4.2 | |
if minor < 2 | |
ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value) | |
# Rails >= 4.2 | |
else | |
ActiveRecord::Type::Boolean.new.type_cast_from_user(value) | |
end | |
# Other | |
else | |
without_rails value | |
end | |
end | |
# as defined in Rails 5: | |
# everything, except empty string and FALSE_VALUES considered as TRUE | |
def without_rails(value) | |
if value == "" | |
nil | |
else | |
!FALSE_VALUES.include?(value) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment