attr_bool_accessor is a gem for adding boolean style attributes to classes.
class User battr_accessor :enabled end u = User.new u.enabled?
Just like any other gem. Just add
to your Gemfile or run
gem install attr_bool_accessor
For basic usage it can be used similarly to an
class User battr_accessor :enabled end
Which provides some basic accessor methods:
u = User.new u.enabled? # => false u.enabled! # set it to true u.enabled? # => true u.enabled = false # set it to a value u.enabled? # => false
The query method
attribute? always returns a
The bang method (
attribute!) sets the attribute to
The writer method (
attribute=) allows you to set the attribute. Values will be converted to boolean.
You can provide multiple attribute names, use strings and use names that include a trailing question mark
class User battr_accessor :first, :second, 'third', :fourth? end
You can also use
attr_boolean as an alias for
class User attr_boolean :enabled end
The following options are accepted:
sets the default (initial) value for the attribute (
false by default)
false to disable the bang (
attribute!) method (
true by default)
false to disable the writer (
attribute=) method (by default the writer is enabled if the bang method is enabled)
true to disable the reader (
attribute) method (this is enabled if the
raw option is set)
Enables raw mode.
This makes a few changes.
Default and assigned values are stored internally in the value provided and not converted to boolean values
reader method is added that allows you to read the raw value.
The query method will always return a boolean.
class User battr_accessor :enabled, default: true, writer: false end class Account battr_accessor :state, default: 3, raw: true end a = Account.new a.state # => 3 a.state? # => true a.state = nil a.state # => nil a.state? # => false
Bug reports and pull requests are welcome on GitHub at https://github.com/marcrohloff/attr_bool_accessor.
The gem is available as open source under the terms of the MIT License.
Created by Yuri Smirnov.