public
Last active

Allowable: A micro-gem DSL for compound conditionals.

  • Download Gist
ALLOWABLE.md
Markdown

Allowable

A micro-gem DSL for compound conditionals.

Allowable lets you decompose large/long conditional chains into readable, testable, and inspectable segments with Ruby blocks.

Installation

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.

About

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, eachwhen?emulates theor` 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.

Usage

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
allowable.gemspec
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Gem::Specification.new do |s|
s.name = 'allowable'
s.summary = ''
s.description = ''
s.version = '0.1.0'
s.platform = Gem::Platform::RUBY
s.files = ['allowable.rb']
s.require_path = '.'
s.author = 'Chris Keele'
s.email = 'dev@chriskeele.com'
s.homepage = ''
s.test_file = '' #'allowable_test.rb'
end
allowable.rb
Ruby
1 2 3 4 5 6 7 8 9 10
module Allowable
def allow(&block)
catch :allowed do
yield
end or false
end
def when?(&block)
throw :allowed, true if yield
end
end
authority_example.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
###
# Inside your Authority initializer
#
class Authority::Authorizer
include Allowable
extend Allowable
end
 
###
# CommentAuthorizer
#
# Example Usage of Allowable in an Authority::Authorizer
#
# Assuming a Comment model attached to a Post:
#
class CommentAuthorizer < Authority::Authorizer
# Fallback
def self.default(ability, user, *args)
user.has_role? :super_admin
end
# Authorization for Comment class (read/create)
def self.readable_by?(user, *args)
allow do
when? { super } # Super calls still work, keeping code dry
when? { user.has_role? :member }
end
end
def self.creatable_by?(user, *args)
allow do
when? { super }
when? { user.has_role?(:member) and not user.shadow_banned? }
when? { user.anonymous? and not User.banned_ips.include?(user.ip_address) }
end
end
# Authorization for Comment instances (edit/destroy)
def updatable_by?(user, *args)
allow do
when? { super }
when? { user.has_role? :author, resource }
when? { user.has_role? :moderator }
when? { user.has_role?(:member) and user.membership.joined_ago.days > 365 }
when_api_enabled(user, resource)
end
end
def deleteable_by?(user, *args)
allow do
when? { super }
when? &:feeling_lucky # also accepts procs
when_api_enabled(user, resource)
end
end
private
 
# Re-use when? statements
def when_api_enabled(user, comment)
response = APIClient.get("/user/#{user.id}/permissions/comments/#{comment.id}")
when? { response.code == 200 }
end
def feeling_lucky
[true, false].sample
end
end
license.md
Markdown

The MIT License (MIT)

Copyright (c) 2013 Chris Keele

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@adamhunter - I was a bit slow to understand this, but because I didn't understand how throw and catch work in Ruby, but essentially if any when? returns true, the allow returns true, otherwise it's false.

Pretty slick coding.

I'm torn for the same reasons @nathanl is... It is a very pretty DSL that could be optionally enabled by adding something like include Authority::DSL or Authority::DSLAuthorizor. For six lines of code an extension gem doesn't make sense.

I will say its very slick @christhekeele, kudos.

It's too small for a gem period, so I've just refactored this gist to be more copy-paste friendly.

@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.

Hey does updatable_by and deleteable_by need ?'s (e.g. deleteable_by?)

@kramersharp good catch.

Playing with micro-gems, if anybody still uses this. I do, so it seemed like a good candidate.

Let me know if you try it out as a gem and it doesn't work.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.