Skip to content

Instantly share code, notes, and snippets.

@attenzione
Last active June 11, 2020 08:22
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save attenzione/a7ffe04ca28c57ffaa14 to your computer and use it in GitHub Desktop.
Save attenzione/a7ffe04ca28c57ffaa14 to your computer and use it in GitHub Desktop.
Ruby: casting to boolean value
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