DefaultOptions
Super simple library provides an easy DSL for setting default options in methods.
Installation
Add this line to your application's Gemfile:
gem 'default_options'
And then execute:
$ bundle
Or install it yourself as:
$ gem install default_options
Usage
Let's say you have a method that returns the number of views a particular blog post receives. This method also accepts a hash of options to allow use to limit the number of views returned to a particular date range:
This is a Rails example, but the library works in any Ruby project
def blog_views(opts = {})
= {
:start_date => self.created_at,
:end_date => Time.zone.now
}
= opts.reverse_merge()
self.views.where(:start_date => [:start_date], :end_date => [:end_date]).count
end
With DefaultOptions, this same code would look like:
def blog_views(opts = {})
= defaults_for opts do
start_date self.created_at
end_date Time.zone.now
end
self.views.where(:start_date => .start_date, :end_date => .end_date).count
end
To add this functionality to any Ruby class, just include the library.
require 'default_options' # If you are using Rails, you don't need this line
class AwesomeSauce
include DefautOptions
def rad_thing(opts = {})
…
end
end
Contributing
- Fork it ( https://github.com/mertonium/default_options/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