Attribute Boolean
The purpose of this gem is to provide an attr_boolean shortcut to classes.
This shortcut creates accessors that, when assigned to with a variety of
"falsey" or "truthy" data, can be interpreted as intended.
Installation
Add this line to your application's Gemfile:
gem 'attribute_boolean'And then execute:
$ bundle
Or install it yourself as:
$ gem install attribute_boolean
Usage
In a standard Ruby class, you might have something like this:
class Calculation
include AttributeBoolean
attr_boolean :complete
endThis provides you with the "#{attr}=" and "#{attr}?" methods:
c = Calculation.new
c.complete = "1"
c.complete? #=> true
c.complete = "0"
c.complete? #=> false
c.complete = "yes"
c.complete? #=> true
c.complete = "no"
c.complete? #=> falseThe default values that are interpreted as false is:
[ false, 0, '0', 'f', 'F', 'false', 'FALSE', 'off', 'OFF', 'n', 'N', 'no', 'NO' ]This can be customized globally like this:
AttributeBoolean.false_values = [ "dunno", -1, :negative ]
AttributeBoolean.false_values += [ "no way", 0 ]Or the false_values list can be set individually per attr_boolean call.
Using this option will replace the global list for that attribute.
attr_boolean :complete, false_values: [ 'it is not complete', 'not completed', :nope ]
attr_boolean :in_progress, false_values: Set.new(:no, 'nope')Specify a default value for the attribute that will be used if it (1) hasn't
been set, or (2) has been set to nil. The value passed to default is
casted to a boolean using !!default.
attr_boolean :complete, default: trueAttributeBoolean converts all symbols to strings when evaluating truthiness:
obj.complete = :no
obj.complete? #=> false
obj.complete = :yes
obj.complete? #=> true
Rails
If Rails is loaded when this gem loads, it will automatically inject the
AttributeBoolean module into ActiveRecord::Base, preventing the need to
call include AttributeBoolean on ActiveRecord classes.
Contributing
- Fork it ( https://github.com/[my-github-username]/attribute_boolean/fork )
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request