Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value_to_boolean deprecated; what's a good replacement?

Is there a "cool-kid-approved" replacement for ActiveRecord::ConnectionAdapters::Column.value_to_boolean in rails 3.2?

like image 827
Chris B Avatar asked May 31 '13 00:05

Chris B


2 Answers

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
like image 159
John Naegle Avatar answered Oct 26 '22 07:10

John Naegle


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:

bang bang

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.

Object#present?

From ActiveSupport and the opposite of blank?:

nil.present?     # => false
false.present?   # => false
0.present?       # => true
"false".present? # => true
"".present?      # => false
[].present?      # => false

Array#include?

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.

like image 12
iain Avatar answered Oct 26 '22 07:10

iain