Ruby: How to convert a string to boolean

前端 未结 14 841
抹茶落季
抹茶落季 2020-12-08 13:16

I have a value that will be one of four things: boolean true, boolean false, the string \"true\", or the string \"false\". I want to convert the string to a boolean if it i

14条回答
  •  醉话见心
    2020-12-08 13:43

    In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean. It is working perfectly for me when I deserialize boolean from JSON string.

    https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html

    # app/lib/core_extensions/string.rb
    module CoreExtensions
      module String
        def to_bool
          ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
        end
      end
    end
    

    initialize core extensions

    # config/initializers/core_extensions.rb
    String.include CoreExtensions::String
    

    rspec

    # spec/lib/core_extensions/string_spec.rb
    describe CoreExtensions::String do
      describe "#to_bool" do
        %w[0 f F false FALSE False off OFF Off].each do |falsey_string|
          it "converts #{falsey_string} to false" do
            expect(falsey_string.to_bool).to eq(false)
          end
        end
      end
    end
    

提交回复
热议问题