AttrSetting
Installation
Add this line to your application's Gemfile:
gem 'attr_setting'
And then execute:
$ bundle
Or install it yourself as:
$ gem install attr_setting
Usage
attr_setting provides enhanced functionality to Ruby's attr_accessor.
To use, require the library and extend the module:
require 'attr_setting'
class Config
extend AttrSetting
end
A monkeypatch is available to auto-extend AttrSetting for use in all Module and Class definitions:
require 'attr_setting/core_ext/module'
attr_setting adds default values to attr_accessor in the form of a second argument or block:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo, 'Second argument'
attr_setting(:bar) { 'Block' }
end
config = Config.new
config.foo # => 'Second argument'
config. # => 'Block'
The block is evaluated in the context of the object:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo, 'Foo value'
attr_setting(:bar) { foo }
end
config = Config.new
config.foo # => 'Foo value'
config. # => 'Foo value'
The block is lazily evaluated:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo
attr_setting(:bar) { foo }
end
config = Config.new
config.foo = 'New value'
config. # => 'New value'
attr_setting also adds a couple other features besides default values for attr_accessor.
It adds a predicate method:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo
end
config = Config.new
config.foo? # => false
config.foo = :something
config.foo? # => true
It adds a bang method to reset values to their defaults:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo, 'Default'
end
config = Config.new
config.foo # => 'Default'
config.foo = 'New value'
config.foo # => 'New value'
config.foo!
config.foo # => 'Default'
It treats getters with an argument as setters:
require 'attr_setting'
class Config
extend AttrSetting
attr_setting :foo
end
config = Config.new
config.foo('New value')
config.foo # => 'New value'
Development
After checking out the repo, run bin/setup to install dependencies. Then, run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install.
Contributing
- Fork it ( https://github.com/[my-github-username]/attr_setting/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