Force string to boolean object

Problem

You have a report that expects a boolean. Sometimes the it is run from a job that passes in a boolean. And sometimes it is executed from a controller using a param that comes in as "true" or "false".

How do you ensure "true" and true are both treated as a boolean?

Solution

Force string to boolean using ActiveModel::Type::Boolean.new.cast

irb(main)> ActiveModel::Type::Boolean.new.cast('true')
=> true

irb(main)> ActiveModel::Type::Boolean.new.cast(true)
=> true

Leave a Reply

Your email address will not be published. Required fields are marked *

Up Next:

Force Rails Database Migration

Force Rails Database Migration