attr_bool_accessor is a gem for adding boolean style attributes to classes.
For example:
class User
battr_accessor :enabled
end
u = User.new
u.enabled?Installation
Just like any other gem. Just add
gem "attr_bool_accessor"
to your Gemfile or run
gem install attr_bool_accessor
Usage
For basic usage it can be used similarly to an attr_accessor
class User
battr_accessor :enabled
endWhich 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? # => falseThe query method attribute? always returns a true or false value.
The bang method (attribute!) sets the attribute to true.
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?
endYou can also use attr_boolean as an alias for battr_accessor
class User
attr_boolean :enabled
endOptions
The following options are accepted:
default:
sets the default (initial) value for the attribute (false by default)
bang:
Set to false to disable the bang (attribute!) method (true by default)
writer:
Set to false to disable the writer (attribute=) method (by default the writer is enabled if the bang method is enabled)
reader:
Set to true to disable the reader (attribute) method (this is enabled if the raw option is set)
raw:
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
A reader method is added that allows you to read the raw value.
The query method will always return a boolean.
Examples
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? # => falseContributing
Bug reports and pull requests are welcome on GitHub at https://github.com/marcrohloff/attr_bool_accessor.
License
The gem is available as open source under the terms of the MIT License.
Author
Created by Yuri Smirnov.