Skip to content

Instantly share code, notes, and snippets.

@tamadamas
Created May 14, 2019 10:27
Show Gist options
  • Save tamadamas/78c3473bbd079ed0d1950582aecfe27c to your computer and use it in GitHub Desktop.
Save tamadamas/78c3473bbd079ed0d1950582aecfe27c to your computer and use it in GitHub Desktop.
Rails Typecase from string to boolean
# Rails 5
ActiveModel::Type::Boolean.new.cast('t') # => true
ActiveModel::Type::Boolean.new.cast('true') # => true
ActiveModel::Type::Boolean.new.cast(true) # => true
ActiveModel::Type::Boolean.new.cast('1') # => true
ActiveModel::Type::Boolean.new.cast('f') # => false
ActiveModel::Type::Boolean.new.cast('0') # => false
ActiveModel::Type::Boolean.new.cast('false') # => false
ActiveModel::Type::Boolean.new.cast(false) # => false
ActiveModel::Type::Boolean.new.cast(nil) # => nil
# Rails 4.2
ActiveRecord::Type::Boolean.new.type_cast_from_database(value)
# Rails 4.1 and bellow
ActiveRecord::ConnectionAdapters::Column.value_to_boolean 'f' # => false
ActiveRecord::ConnectionAdapters::Column.value_to_boolean 't' # => true
ActiveRecord::ConnectionAdapters::Column.value_to_boolean '0' # => false
ActiveRecord::ConnectionAdapters::Column.value_to_boolean '1' # => true
ActiveRecord::ConnectionAdapters::Column.value_to_boolean nil # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment