Is there a \"cool-kid-approved\" replacement for ActiveRecord::ConnectionAdapters::Column.value_to_boolean
in rails 3.2?
As jokklan mentioned in the comments, the answer depends on what you want to do with it? Do you want to accepts all kinds of strings and turn them into a real boolean? Or do you control the submitting end as well and can you be more strict?
From strict to more magic:
The double bang method converts any object to a real boolean. The first bang turns it into it's opposite, the second to it's proper boolean value.
Basically, nil
and false
will become false
, everything else will become true
.
!!nil # => false
!!false # => false
!!0 # => true
!!true # => true
!!"" # => true
!!"false" # => true
!![] # => true
Good for exporting to json, but not really needed when kept inside Ruby.
From ActiveSupport and the opposite of blank?
:
nil.present? # => false
false.present? # => false
0.present? # => true
"false".present? # => true
"".present? # => false
[].present? # => false
Specify special strings that are falsy, or truthy to you:
not [nil, false, 0, '0', 'f', 'F', 'false', 'FALSE'].include?(value.presence)
Or the other way round:
[true, 1, '1', 't', 'T', 'true', 'TRUE'].include?(value)
These are handy if you are handling form submissions with checkboxes, or handling external input and you want to be more lenient. You can of course decide for yourself what you want to accept.
In Rails 4.2, this looks like a possible way to do it:
ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
Which under the covers is going to do this
if value == ''
nil
else
ConnectionAdapters::Column::TRUE_VALUES.include?(value)
end
Or in Rails 5:
ActiveRecord::Type::Boolean.new.cast(value)
Which seems to end up here:
def cast_value(value)
if value == ''
nil
else
!FALSE_VALUES.include?(value)
end
end
ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
return nil if the value is nil/empty('').
ActiveRecord::Type::Boolean.new.type_cast_from_database(nil) # => nil
ActiveRecord::Type::Boolean.new.type_cast_from_database('') # => nil
I would prefer !!
with ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
for converting input value to boolean
!!ActiveRecord::Type::Boolean.new.type_cast_from_database(nil) # => false
!!ActiveRecord::Type::Boolean.new.type_cast_from_database('') # => false
It appears that value_to_boolean
isn't really deprecated in Rails 4 http://www.rubydoc.info/docs/rails/ActiveRecord/ConnectionAdapters/Column.value_to_boolean