Shield is a policies clean API for using in Rails applications. The intention is to have an easy way to use policies inside Rails applications with a clean and well defined API.
The basic idea is to have some PORO to handle read operations without in case those operations get a little bit complex.
The following resources brought some inspirations to the lib:
Rails - the Missing Parts - Policies
Doman Driven Rails - Yan Pritzker
7 Patterns to Refactor Fat ActiveRecord Models
Add this line to your application's Gemfile:
gem 'shield'
And then execute:
$ bundle
Or install it yourself as:
$ gem install shield
class IsActiveUser
def initialize(user)
@user = user
end
def validate
user.email_confirmed? && user.last_login_at > 14.days.ago
end
private
attr_reader :user
end
class Subscriber
include Shield
def subscribe(user)
policies.with(IsActiveUser.new(user)).apply
end
endWhen calling apply! instead of apply shield will generate an exception
dynamically for you with the error message that you specified the name will be
based on the policy name plus the word error; ex. IsActiveUserError
class IsActiveUser
attr_reader :error
def initialize(user, error)
@error = error
@user = user
end
def validate
user.email_confirmed? && user.last_login_at > 14.days.ago
end
private
attr_reader :user
end
class Subscriber
include Shield
def subscribe(user)
policies.with(IsActiveUser.new(user, 'Policy failed')).apply!
end
end- Fork it ( https://github.com/[my-github-username]/shield/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