A micro-gem DSL for compound conditionals.
Allowable lets you decompose large/long conditional chains into readable, testable, and inspectable segments with Ruby blocks.
If using bundler, add to your Gemfile:
$ echo "gem 'allowable', :git => 'git://gist.github.com/5816657.git'" >> Gemfile
$ bundle install
Or, steal allowable.rb
and put it wherever you please.
Standard conditional statements are evaluated as a single expression, meaning you may have to split them akwardly across multiple lines. It can be hard to inspect intermediary conditions, and your test coverage can't inform you that you've fully flexed each case.
Within an 'allowblock, each
when?emulates the
or` operator:
each condition will be evaulated in turn until one is found to be true,
lazily evaluating your criteria.
Originally thrown together as a proposed augmentation to Authority. I also regularly use it in Sanitizer classes for Rails parameters.
A more 'real-world', demonstrative use-case can be found in authority_example.rb
.
class Database
include Allowable
def drop
drop! if can_drop? User.current
end
def can_drop?(user)
allow do
when? do
puts "What's the password?"
gets.chomp == self.admin_password
end
when? { user.admin? }
when? { self.empty? }
when? { self.null_object? }
when? { self.last_accessed > 2.years.ago }
end
end
end
@christhekeele - Looks good. I'm going to add a link to the wiki so that people who want to use this style can find your example easily.