The behavior switching framework. inspired by DCI.
- Ruby >= 2.0.0
- Tested ruby version:
- 2.0.0
- 2.1.0
- 2.1.1
- head
- Tested ruby version:
Add this line to your application's Gemfile:
gem 'blue_print', '~> 1.3.0'
BluePrint provides some integrations. Now supported libraries:
- Ruby on Rails >= 3.1
- Grape
- Draper
- RSpec
BluePrint provides a generator to create templates of a context and behaviros.
$ rails generate blue_print staff user:staff_user
create app/blue_prints/staff_context.rb
create app/blue_prints/staff_context/staff_user.rb
invoke rspec
create spec/blue_prints/staff_context_spec.rb
create spec/blue_prints/staff_context/staff_user_spec.rb
Contexts inherit from BluePrint::Context
, live in your app/blue_prints
directory.
This block is used to decide if this context active or not. env
is the BluePrint.env
. self
is passed via BluePrint::Environment#context
. By default, this is set as active_if { false }
.
class StaffContext < BluePrint::Context
active_if do |env|
current_user.try(:staff?)
end
end
And you can define named active if:
# lib/active_ifs/staff.rb
BluePrint::ActiveIf.new(:staff) do |env|
current_user.try(:staff?)
end
# app/blue_prints/staff_context.rb
class StaffContext < BluePrint::Context
active_if :staff
end
Contexts has casting. This is used to decide classes cast as behaviors if this context active.
class StaffContext < BluePrint::Context
cast ::User, as: [StaffUser]
end
StaffContext.casting
# =>
# {
# User => [ StaffUser ]
# }
Behaviors extended by BluePrint::Behavior
, live in your app/blue_prints/{context}
directory.
# app/blue_prints/staff_context/staff_user.rb
module StaffContext::StaffUser
extend BluePrint::Behavior
end
Behaviors can have some methods.
# app/blue_prints/staff_context/staff_user.rb
module StaffContext::StaffUser
extend BluePrint::Behavior
def user_name
"staff"
end
end
# app/models/user.rb
class User < ActiveRecord::Base
def user_name
"#{name} san"
end
end
user = User.new(name: "Magnet")
StaffContext.deactivate!
user.user_name # => "Magnet san"
StaffContext.activate!
user.user_name # => "staff"
Behaviors can have some class methods.
# app/blue_prints/staff_context/staff_user.rb
module StaffContext::StaffUser
extend BluePrint::Behavior
module ClassMethods
def find(id)
where(id: id, staff: true).first!
end
end
end
# app/models/user.rb
class User < ActiveRecord::Base
end
user = User.create(staff: false)
StaffContext.deactivate!
User.find(user.id) == user # => true
StaffContext.activate!
User.find(user.id) # => raise ActiveRecord::NotFound
BluePrint::Helper
provides #within_context_of
and #without_context_of
.
This module includes automatically to some classes. see lib/blue_print/integration.
- Fork it ( http://github.com/magnet-inc/blue_print/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 new Pull Request