LoginSignup
0
0

More than 1 year has passed since last update.

ActiveRecordの真偽値の判定

Last updated at Posted at 2021-05-17

ソースコードを見ていて少し意外な値もfalseになることを知りました。
( https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html#:~:text=Constants-,false_values,-%3D )
バージョンは6.0.3.6です。

ActiveRecord::Type::Boolean.new.method(:cast).source_location
# => path/to/gems/activemodel-6.0.3.6/lib/active_model/type/value.rb", 37
# path/to/gems/activemodel-6.0.3.6/lib/active_model/type/value.rb"
module ActiveModel
  module Type
    class Value
# ....
      def cast(value)
        cast_value(value) unless value.nil?
      end
      private
      def cast_value(value) # :doc:
        value
      end
      # ここのcast_valueをActiveModel::Type::Booleanではオーバーライドしており真偽値のキャストでは下のメソッドが呼ばれます。
    end
  end
end
# path/to/gems/activemodel-6.0.3.6/lib/active_model/type/boolean.rb
module ActiveModel
  module Type
    class Boolean < Value
      FALSE_VALUES = [
        false, 0,
        "0", :"0",
        "f", :f,
        "F", :F,
        "false", :false,
        "FALSE", :FALSE,
        "off", :off,
        "OFF", :OFF,
      ].to_set.freeze
# ....
      private
        def cast_value(value)
          if value == ""
            nil
          else
            !FALSE_VALUES.include?(value)
          end
        end
    end
  end
end
ActiveRecord::Type::Boolean.new.cast :f
# => false
ActiveRecord::Type::Boolean.new.cast :off
# => false

みたいな。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0