Skip to content

Instantly share code, notes, and snippets.

@christhekeele
Last active May 16, 2023 10:27
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save christhekeele/5816657 to your computer and use it in GitHub Desktop.
Save christhekeele/5816657 to your computer and use it in GitHub Desktop.
Allowable: A Ruby gem DSL for compound conditionals.
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

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
module Allowable
def allow(&block)
catch :allowed do
yield
end or false
end
def when?(&block)
throw :allowed, true if yield
end
end
###
# 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

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.

@nathanl
Copy link

nathanl commented Jun 19, 2013

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

@adamhunter
Copy link

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.

@christhekeele
Copy link
Author

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

@nathanl
Copy link

nathanl commented Jun 24, 2013

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

@kramersharp
Copy link

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

@christhekeele
Copy link
Author

@kramersharp good catch.

@christhekeele
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment