EasyBool

Tiny boolean casting utility for Ruby.

Is this a world-changing gem?
Absolutely not.

Could you write this yourself in 30 seconds?
Also yes.

But sometimes fun little projects are the best way to learn how gems work, and typing:

ActiveModel::Type::Boolean.new.cast(value)

every single time felt unnecessarily dramatic.

So here we are.


Installation

Add this line to your application's Gemfile:

gem "easy_bool"

And then execute:

bundle install

Or install directly:

gem install easy_bool

Usage

require "easy_bool"

EasyBool.cast("true")
# => true

EasyBool.cast("false")
# => false

EasyBool.cast("1")
# => true

EasyBool.cast("0")
# => false

EasyBool.cast(nil)
# => false

Supported Truthy Values

true
1
"1"
"true"
"t"
"yes"
"y"
"on"

Whitespace and casing are ignored:

EasyBool.cast(" TRUE ")
# => true

Supported Falsey Values

false
0
"0"
"false"
"f"
"no"
"n"
"off"
nil

Defaults

Unknown values fall back to the provided default.

EasyBool.cast("maybe")
# => false

EasyBool.cast("maybe", default: true)
# => true

Convenience Methods

EasyBool.true?("yes")
# => true

EasyBool.false?("off")
# => true

Rails Example

hidden = EasyBool.cast(params[:hidden])

if hidden
  # do something
end

Why Does This Exist?

Mostly because:

  • building tiny tools is fun
  • learning how gems work is useful
  • overengineering small problems is a developer tradition

And honestly:

EasyBool.cast(value)

just feels nicer.


Development

Run tests:

bundle exec rspec

Interactive console:

bin/console

Build gem:

bundle exec rake build

Install locally:

gem install pkg/easy_bool-x.x.x.gem

Contributing

If you somehow discover a groundbreaking boolean edge case, PRs are welcome.


License

MIT