├── .gitignore ├── .rspec ├── .travis.yml ├── Gemfile-rails-4.0.x ├── Gemfile-rails-4.1.x ├── Gemfile-rails-4.2.x ├── MIT-LICENSE ├── README.md ├── Rakefile ├── db └── migrate │ ├── 20120831163952_create_rules.rb │ └── 20120831173835_create_rule_sets.rb ├── lib ├── assets │ └── javascripts │ │ └── rules │ │ └── active_admin.js ├── rules.rb ├── rules │ ├── config.rb │ ├── engine.rb │ ├── evaluators.rb │ ├── evaluators │ │ ├── definitions.rb │ │ └── evaluator.rb │ ├── extensions │ │ ├── active_admin │ │ │ └── dsl.rb │ │ └── active_model │ │ │ ├── absence_validator.rb │ │ │ └── parameter_key_validator.rb │ ├── has_rules.rb │ ├── parameters.rb │ ├── parameters │ │ ├── attribute.rb │ │ ├── constant.rb │ │ ├── constant_definitions.rb │ │ └── parameter.rb │ ├── rule.rb │ ├── rule_set.rb │ └── version.rb └── tasks │ └── rules_tasks.rake ├── rules.gemspec └── spec ├── dummy ├── README.rdoc ├── Rakefile ├── app │ ├── admin │ │ ├── dashboards.rb │ │ └── orders.rb │ ├── assets │ │ ├── images │ │ │ └── edit_example.png │ │ ├── javascripts │ │ │ ├── active_admin.js │ │ │ └── application.js │ │ └── stylesheets │ │ │ ├── active_admin.css.scss │ │ │ └── application.css │ ├── controllers │ │ ├── application_controller.rb │ │ └── orders_controller.rb │ ├── helpers │ │ └── application_helper.rb │ ├── mailers │ │ └── .gitkeep │ ├── models │ │ ├── .gitkeep │ │ ├── admin_user.rb │ │ └── order.rb │ └── views │ │ ├── layouts │ │ └── application.html.erb │ │ └── orders │ │ └── show.html.haml ├── bin │ ├── bundle │ ├── rails │ ├── rake │ └── setup ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── active_admin.rb │ │ ├── assets.rb │ │ ├── backtrace_silencers.rb │ │ ├── cookies_serializer.rb │ │ ├── devise.rb │ │ ├── filter_parameter_logging.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── secret_token.rb │ │ ├── session_store.rb │ │ └── wrap_parameters.rb │ ├── locales │ │ ├── devise.en.yml │ │ └── en.yml │ ├── routes.rb │ └── secrets.yml ├── db │ ├── migrate │ │ ├── 20120821181654_create_orders.rb │ │ ├── 20120901044842_devise_create_admin_users.rb │ │ ├── 20120901044906_create_admin_notes.rb │ │ ├── 20120901044907_move_admin_notes_to_comments.rb │ │ ├── 20121029183622_create_rules.rules.rb │ │ └── 20121029183623_create_rule_sets.rules.rb │ ├── schema.rb │ └── seeds.rb ├── lib │ └── assets │ │ └── .gitkeep ├── log │ └── .gitkeep ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ └── favicon.ico └── script │ └── rails ├── rules ├── evaluators │ ├── definitions_spec.rb │ └── evaluator_spec.rb ├── evaluators_spec.rb ├── parameters │ └── attribute_spec.rb ├── parameters_spec.rb ├── rule_set_spec.rb └── rule_spec.rb └── spec_helper.rb /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle/ 2 | log/*.log 3 | pkg/ 4 | spec/dummy/db/*.sqlite3 5 | spec/dummy/log/*.log 6 | spec/dummy/tmp/ 7 | spec/dummy/.sass-cache 8 | *.gem 9 | Gemfile.lock 10 | .DS_Store 11 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --color 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | sudo: false 3 | 4 | rvm: 5 | - 2.3.3 6 | 7 | notifications: 8 | email: false 9 | 10 | script: 11 | - (cd spec/dummy && bundle exec rake db:setup) 12 | - bundle exec rspec 13 | 14 | gemfile: 15 | - Gemfile-rails-4.0.x 16 | - Gemfile-rails-4.1.x 17 | - Gemfile-rails-4.2.x 18 | -------------------------------------------------------------------------------- /Gemfile-rails-4.0.x: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | # Declare your gem's dependencies in rules.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | # jquery-rails is used by the dummy application 9 | gem "activeadmin", '1.0.0.pre2' 10 | gem "coffee-rails" 11 | gem 'devise', '~> 3.2' 12 | gem "formtastic" 13 | gem "haml" 14 | gem "jquery-rails" 15 | gem "sass-rails" 16 | gem "rails", '~> 4.0.13' 17 | 18 | gem "sqlite3", platforms: [:ruby, :mswin, :mingw] 19 | 20 | # for JRuby 21 | gem "jdbc-sqlite3", platforms: :jruby 22 | 23 | # Declare any dependencies that are still in development here instead of in 24 | # your gemspec. These might include edge Rails or gems from your path or 25 | # Git. Remember to move these dependencies to your gemspec before releasing 26 | # your gem to rubygems.org. 27 | 28 | # To use debugger 29 | # gem 'debugger' 30 | -------------------------------------------------------------------------------- /Gemfile-rails-4.1.x: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | # Declare your gem's dependencies in rules.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | # jquery-rails is used by the dummy application 9 | gem "activeadmin", '1.0.0.pre2' 10 | gem "coffee-rails" 11 | gem 'devise', '~> 3.2' 12 | gem "formtastic" 13 | gem "haml" 14 | gem "jquery-rails" 15 | gem "sass-rails" 16 | gem "rails", '~> 4.1.0' 17 | 18 | gem "sqlite3", platforms: [:ruby, :mswin, :mingw] 19 | 20 | # for JRuby 21 | gem "jdbc-sqlite3", platforms: :jruby 22 | 23 | # Declare any dependencies that are still in development here instead of in 24 | # your gemspec. These might include edge Rails or gems from your path or 25 | # Git. Remember to move these dependencies to your gemspec before releasing 26 | # your gem to rubygems.org. 27 | 28 | # To use debugger 29 | # gem 'debugger' 30 | -------------------------------------------------------------------------------- /Gemfile-rails-4.2.x: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | # Declare your gem's dependencies in rules.gemspec. 4 | # Bundler will treat runtime dependencies like base dependencies, and 5 | # development dependencies will be added by default to the :development group. 6 | gemspec 7 | 8 | # jquery-rails is used by the dummy application 9 | gem "activeadmin", '1.0.0.pre2' 10 | gem "coffee-rails" 11 | gem 'devise', '~> 3.2' 12 | gem "formtastic" 13 | gem "haml" 14 | gem "jquery-rails" 15 | gem "sass-rails" 16 | gem "rails", '~> 4.2.0' 17 | 18 | gem "sqlite3", platforms: [:ruby, :mswin, :mingw] 19 | 20 | # for JRuby 21 | gem "jdbc-sqlite3", platforms: :jruby 22 | 23 | # Declare any dependencies that are still in development here instead of in 24 | # your gemspec. These might include edge Rails or gems from your path or 25 | # Git. Remember to move these dependencies to your gemspec before releasing 26 | # your gem to rubygems.org. 27 | 28 | # To use debugger 29 | # gem 'debugger' 30 | -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2012 YOURNAME 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Rules 2 | ========= 3 | [![build status](https://secure.travis-ci.org/azach/rules.png?branch=master)](https://secure.travis-ci.org/azach/rules) [![Code Climate](https://codeclimate.com/badge.png)](https://codeclimate.com/github/azach/rules) 4 | 5 | A Ruby gem engine that allows you to add customizable business rules to any ActiveRecord model. Rules integrates with ActiveAdmin to make it trivial to allow admin users to create rules on the fly for your models. 6 | 7 | Installation 8 | ------------ 9 | Add it to your Gemfile: 10 | 11 | ```ruby 12 | gem "rules" 13 | ``` 14 | 15 | Update your schema: 16 | 17 | ```ruby 18 | rake rules:install:migrations 19 | rake db:migrate 20 | ``` 21 | 22 | to create the required tables to store your rules. 23 | 24 | Setting Up Rules 25 | ------------ 26 | To use rules on a model, include ```Rules::HasRules```. You can also optionally define any attributes that are available for that model using ```has_rule_attributes```. 27 | 28 | This will allow the user to build rules against this attribute. For example, you may want to allow users to build rules against the email address in the order. In this case, your model would look like: 29 | 30 | ```ruby 31 | class Order < ActiveRecord::Base 32 | include Rules::HasRules 33 | 34 | has_rule_attributes({ 35 | customer_email: { 36 | name: "customer email address" 37 | type: :string # see Rules::Parameters::Parameter::VALID_TYPES for a full list 38 | } 39 | }) 40 | end 41 | ``` 42 | 43 | To evaluate a set of a rules, use the ```rules_pass?``` method on the instance. You may also pass the values of the attributes that you allowed users to define rules against at this point. 44 | 45 | For example: 46 | 47 | ```ruby 48 | order = Order.new 49 | order.email_address = "morbo@example.com" 50 | order.rules_pass?(customer_email: order.email_address) 51 | ``` 52 | 53 | Defining Rules 54 | ------------ 55 | Rules are meant to be defined by business users using an admin interface. For this reason, the gem provides integration with ActiveAdmin to make this easier. 56 | 57 | There are two helper methods you can use, one for your show action and one for your form. 58 | 59 | For the show action: 60 | 61 | ```ruby 62 | show_rules 63 | ``` 64 | 65 | For the form action: 66 | 67 | ```ruby 68 | f.has_rules 69 | ``` 70 | 71 | This will give you something like: 72 | 73 | ![ActiveAdmin form for editing rules](https://github.com/azach/rules/raw/master/spec/dummy/app/assets/images/edit_example.png) 74 | 75 | However, rules are defined using keys and values, so you can easily use your own custom solution. 76 | 77 | ```ruby 78 | rule = Rules::Rule.new(lhs_parameter_key: 'day_of_week', evaluator_key: 'equals', rhs_parameter_raw: 'Sunday') 79 | rule.lhs_parameter_value 80 | => 'Sunday' # (or the current day of week) 81 | rule.evaluate 82 | => true 83 | 84 | Order.has_rule_attributes(customer_email: { name: "Customer's email address" }) 85 | order = Order.new 86 | rule_set = Rules::RuleSet.new(source: order) 87 | 88 | rule = Rules::Rule.new(rule_set: rule_set, lhs_parameter_key: 'customer_email', evaluator_key: 'matches', rhs_parameter_raw: 'example.com$') 89 | rule.lhs_parameter_value 90 | => nil # we didn't pass anything in 91 | rule.rhs_parameter_value 92 | => /example.com$/ # this is a Regexp class 93 | rule.evaluate(customer_email: 'john@example.com') 94 | => true 95 | rule.evaluate(customer_email: 'john@example.net') 96 | => false 97 | ``` 98 | 99 | Configuration 100 | ------------ 101 | You can add an initializer to configure default options. 102 | 103 | ```ruby 104 | Rules.configure do |config| 105 | config.errors_are_false = true # return false if an evaluator raises an error (true by default) 106 | config.missing_attributes_are_nil = true # return nil when a value is not passed for an attribute parameter 107 | end 108 | ``` 109 | 110 | Default Constants 111 | ------------ 112 | TODO 113 | 114 | Default Evaluators 115 | ------------ 116 | TODO 117 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | begin 3 | require 'bundler/setup' 4 | rescue LoadError 5 | puts 'You must `gem install bundler` and `bundle install` to run rake tasks' 6 | end 7 | begin 8 | require 'rdoc/task' 9 | rescue LoadError 10 | require 'rdoc/rdoc' 11 | require 'rake/rdoctask' 12 | RDoc::Task = Rake::RDocTask 13 | end 14 | 15 | RDoc::Task.new(:rdoc) do |rdoc| 16 | rdoc.rdoc_dir = 'rdoc' 17 | rdoc.title = 'Rules' 18 | rdoc.options << '--line-numbers' 19 | rdoc.rdoc_files.include('README.rdoc') 20 | rdoc.rdoc_files.include('lib/**/*.rb') 21 | end 22 | 23 | 24 | 25 | 26 | Bundler::GemHelper.install_tasks 27 | 28 | require 'rake/testtask' 29 | 30 | Rake::TestTask.new(:test) do |t| 31 | t.libs << 'lib' 32 | t.libs << 'spec' 33 | t.pattern = 'spec/**/*_spec.rb' 34 | t.verbose = false 35 | end 36 | 37 | 38 | task :default => :spec 39 | -------------------------------------------------------------------------------- /db/migrate/20120831163952_create_rules.rb: -------------------------------------------------------------------------------- 1 | class CreateRules < ActiveRecord::Migration 2 | def change 3 | create_table :rules_rules do |t| 4 | t.belongs_to :rule_set 5 | t.text :expression 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /db/migrate/20120831173835_create_rule_sets.rb: -------------------------------------------------------------------------------- 1 | class CreateRuleSets < ActiveRecord::Migration 2 | def change 3 | create_table :rules_rule_sets do |t| 4 | t.belongs_to :source, polymorphic: true 5 | t.string :evaluation_logic 6 | 7 | t.timestamps 8 | end 9 | end 10 | end 11 | -------------------------------------------------------------------------------- /lib/assets/javascripts/rules/active_admin.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | $('.rules_rule_set select[name*="[lhs_parameter_key]"]').on('change', function(ev) { 3 | var $rawInput; 4 | var selectedType; 5 | 6 | $rawInput = $(this).parent('li').siblings('[id*="rhs_parameter_raw_input"]').find('input'); 7 | selectedType = $(this).find(':selected').data('type'); 8 | 9 | $rawInput.get(0).type = selectedType; 10 | }); 11 | 12 | $('.rules_rule_set select[name*="[evaluator_key]"]').on('change', function(ev) { 13 | var $rhsInputs; 14 | var requiresRHS; 15 | 16 | $rawInputs = $(this).parent('li').siblings('[id*="rhs_parameter"]').find('input, select'); 17 | requiresRHS = $(this).find(':selected').data('requires-rhs'); 18 | 19 | $rawInputs.prop('disabled', !requiresRHS); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /lib/rules.rb: -------------------------------------------------------------------------------- 1 | require 'rules/engine' 2 | require 'rules/extensions/active_model/absence_validator' 3 | require 'rules/extensions/active_model/parameter_key_validator' 4 | require 'rules/config' 5 | require 'rules/evaluators' 6 | require 'rules/evaluators/definitions' 7 | require 'rules/has_rules' 8 | require 'rules/parameters' 9 | require 'rules/parameters/constant_definitions' 10 | require 'rules/rule' 11 | require 'rules/rule_set' 12 | 13 | module Rules 14 | def self.config 15 | @config ||= Config.instance 16 | end 17 | 18 | def self.configure 19 | yield config 20 | end 21 | 22 | def self.evaluators 23 | @evaluators ||= Evaluators.list 24 | end 25 | 26 | def self.constants 27 | @constants ||= Parameters.constants 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /lib/rules/config.rb: -------------------------------------------------------------------------------- 1 | require 'singleton' 2 | 3 | class Rules::Config 4 | include Singleton 5 | 6 | attr_accessor :errors_are_false, :missing_attributes_are_nil 7 | 8 | def initialize 9 | self.errors_are_false = true 10 | self.missing_attributes_are_nil = true 11 | end 12 | 13 | def missing_attributes_are_nil? 14 | !!missing_attributes_are_nil 15 | end 16 | 17 | def errors_are_false? 18 | !!errors_are_false 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /lib/rules/engine.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | class Engine < ::Rails::Engine 3 | isolate_namespace Rules 4 | 5 | initializer :active_admin do 6 | if defined? ActiveAdmin 7 | require 'rules/extensions/active_admin/dsl' 8 | ActiveAdmin.application.javascripts << 'rules/active_admin.js' 9 | end 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /lib/rules/evaluators.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module Evaluators 3 | require 'rules/evaluators/evaluator' 4 | 5 | @@list ||= {} 6 | 7 | def self.list 8 | @@list 9 | end 10 | 11 | def self.define_evaluator(key, &block) 12 | raise 'Evaluator already exists' if @@list[key] 13 | evaluator = Evaluator.new(key) 14 | evaluator.instance_eval(&block) if block_given? 15 | @@list[key] = evaluator 16 | end 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /lib/rules/evaluators/definitions.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module Evaluators 3 | define_evaluator :equals do 4 | self.evaluation_method = ->(lhs, rhs) { lhs == rhs } 5 | self.requires_rhs = true 6 | end 7 | 8 | define_evaluator :not_equals do 9 | self.evaluation_method = ->(lhs, rhs) { lhs != rhs } 10 | self.name = 'does not equal' 11 | self.requires_rhs = true 12 | end 13 | 14 | define_evaluator :contains do 15 | self.evaluation_method = ->(lhs, rhs) { lhs.include?(rhs) } 16 | self.name = 'contains' 17 | self.requires_rhs = true 18 | end 19 | 20 | define_evaluator :not_contains do 21 | self.evaluation_method = ->(lhs, rhs) { !lhs.include?(rhs) } 22 | self.name = 'does not contain' 23 | end 24 | 25 | define_evaluator :nil do 26 | self.evaluation_method = ->(lhs) { lhs.nil? } 27 | self.name = 'exists' 28 | self.requires_rhs = false 29 | end 30 | 31 | define_evaluator :not_nil do 32 | self.evaluation_method = ->(lhs) { !lhs.nil? } 33 | self.name = 'does not exist' 34 | self.requires_rhs = false 35 | end 36 | 37 | define_evaluator :matches do 38 | self.evaluation_method = ->(lhs, rhs) { !!(lhs =~ rhs) } 39 | self.name = 'matches' 40 | self.type_for_rhs = :regexp 41 | self.requires_rhs = true 42 | end 43 | 44 | define_evaluator :not_matches do 45 | self.evaluation_method = ->(lhs, rhs) { !(lhs =~ rhs) } 46 | self.name = 'does not match' 47 | self.type_for_rhs = :regexp 48 | self.requires_rhs = true 49 | end 50 | 51 | define_evaluator :less_than do 52 | self.evaluation_method = ->(lhs, rhs) { lhs < rhs } 53 | self.name = 'less than' 54 | self.requires_rhs = true 55 | end 56 | 57 | define_evaluator :less_than_or_equal_to do 58 | self.evaluation_method = ->(lhs, rhs) { lhs <= rhs } 59 | self.name = 'less than or equal to' 60 | self.requires_rhs = true 61 | end 62 | 63 | define_evaluator :greater_than do 64 | self.evaluation_method = ->(lhs, rhs) { lhs > rhs } 65 | self.name = 'greater than' 66 | self.requires_rhs = true 67 | end 68 | 69 | define_evaluator :greater_than_or_equal_to do 70 | self.evaluation_method = ->(lhs, rhs) { lhs >= rhs } 71 | self.name = 'greater than or equal to' 72 | self.requires_rhs = true 73 | end 74 | end 75 | end 76 | -------------------------------------------------------------------------------- /lib/rules/evaluators/evaluator.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module Evaluators 3 | class Evaluator 4 | attr_accessor :evaluation_method, :requires_rhs, :type_for_rhs, :name 5 | 6 | def initialize(key) 7 | @name = key.to_s 8 | @requires_rhs = true 9 | end 10 | 11 | def evaluate(lhs, rhs = nil) 12 | raise 'Unknown evaluation method' unless evaluation_method 13 | 14 | begin 15 | requires_rhs? ? evaluation_method.call(lhs, rhs) : evaluation_method.call(lhs) 16 | rescue StandardError => ex 17 | return false if Rules.config.errors_are_false? 18 | raise ex 19 | end 20 | end 21 | 22 | def requires_rhs? 23 | @requires_rhs 24 | end 25 | 26 | def to_s 27 | @name 28 | end 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /lib/rules/extensions/active_admin/dsl.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin::FormBuilder.class_eval do 2 | def has_rules 3 | inputs 'Rules' do 4 | semantic_fields_for :rule_set do |rules_rule_set_form| 5 | rules_rule_set_form.has_many :rules do |rules_rule_form| 6 | rules_rule_form.input :lhs_parameter_key, :label => 'Left hand side', collection: rules_parameter_collection(object.rule_set) 7 | rules_rule_form.input :evaluator_key, :label => 'Evaluator', :as => :select, :collection => Rules.evaluators.map {|key, evaluator| [evaluator.name, key, {:'data-requires-rhs' => evaluator.requires_rhs?}] }.sort_by {|name, key| name } 8 | rules_rule_form.input :rhs_parameter_raw, :label => 'Enter a value', :wrapper_html => { :class => "rules_rhs_parameter" } 9 | rules_rule_form.input :rhs_parameter_key, :label => 'Or choose a value', collection: rules_parameter_collection(object.rule_set), :wrapper_html => { :class => "rules_rhs_parameter" } 10 | end 11 | rules_rule_set_form.input :evaluation_logic, :as => :select, :label => 'Must match', collection: [['All Rules', 'all'], ['Any Rules', 'any']] 12 | end 13 | end 14 | end 15 | 16 | def rules_parameter_collection(rule_set) 17 | @rules_parameter_collection ||= Rules.constants.merge(rule_set.try(:attributes) || {}).map {|key, const| [const.name, key, {:'data-type' => const.try(:type) || 'string'}] } 18 | end 19 | end 20 | 21 | ActiveAdmin::Views::Pages::Show.class_eval do 22 | def show_rules 23 | panel "Rules" do 24 | div resource.rule_set.evaluation_logic == 'any' ? 'Must match any rule' : 'Must match all rules' 25 | table_for resource.rule_set.rules do |rule| 26 | column('Left hand side') { |rule| rule.lhs_parameter.to_s } 27 | column('Condition') { |rule| rule.evaluator } 28 | column('Right hand side') { |rule| rule.rhs_parameter.to_s } 29 | end 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /lib/rules/extensions/active_model/absence_validator.rb: -------------------------------------------------------------------------------- 1 | class AbsenceValidator < ActiveModel::EachValidator 2 | def validate_each(record, attribute, value) 3 | record.errors.add attribute, (options[:message] || "must be blank") unless value.blank? 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /lib/rules/extensions/active_model/parameter_key_validator.rb: -------------------------------------------------------------------------------- 1 | class ParameterKeyValidator < ActiveModel::EachValidator 2 | def validate_each(record, attribute, value) 3 | unless record.valid_parameter_keys.include?(value) 4 | record.errors.add attribute, (options[:message] || "is not a valid parameter") 5 | end 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /lib/rules/has_rules.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module HasRules 3 | def self.included(base) 4 | base.instance_eval do 5 | has_one :rule_set, class_name: 'Rules::RuleSet', as: :source, dependent: :destroy 6 | 7 | accepts_nested_attributes_for :rule_set, allow_destroy: true 8 | 9 | def has_rule_attributes(attributes = {}) 10 | Rules::RuleSet.set_attributes_for(self, attributes) 11 | end 12 | end 13 | end 14 | 15 | def rule_set 16 | super || self.build_rule_set(source: self) 17 | end 18 | 19 | def rules_pass?(options = {}) 20 | rule_set.nil? || rule_set.evaluate(options) 21 | end 22 | end 23 | end 24 | -------------------------------------------------------------------------------- /lib/rules/parameters.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module Parameters 3 | require 'rules/parameters/parameter' 4 | require 'rules/parameters/attribute' 5 | require 'rules/parameters/constant' 6 | 7 | @@constants ||= {} 8 | 9 | def self.constants 10 | @@constants 11 | end 12 | 13 | def self.define_constant(key, &block) 14 | raise "Constant #{key} already exists" if @@constants[key] 15 | constant = Constant.new(key: key) 16 | constant.instance_eval(&block) if block_given? 17 | @@constants[key] = constant 18 | end 19 | end 20 | end 21 | -------------------------------------------------------------------------------- /lib/rules/parameters/attribute.rb: -------------------------------------------------------------------------------- 1 | require 'rules/parameters/parameter' 2 | 3 | module Rules::Parameters 4 | class Attribute < Parameter 5 | def evaluate(attributes = {}) 6 | if Rules.config.missing_attributes_are_nil? 7 | attributes[key] 8 | else 9 | attributes.fetch(key) 10 | end 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /lib/rules/parameters/constant.rb: -------------------------------------------------------------------------------- 1 | require 'rules/parameters/parameter' 2 | 3 | module Rules::Parameters 4 | class Constant < Parameter 5 | attr_accessor :evaluation_method 6 | 7 | def evaluate(attributes = {}) 8 | raise 'Unknown evaluation method' unless evaluation_method 9 | evaluation_method.call 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /lib/rules/parameters/constant_definitions.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | module Parameters 3 | define_constant :today do 4 | self.name = 'current date' 5 | self.type = :date 6 | self.evaluation_method = -> { Time.now.utc.to_date } 7 | end 8 | 9 | define_constant :day_of_week do 10 | self.name = 'day of week' 11 | self.evaluation_method = -> { Date::DAYNAMES[Time.now.utc.to_date.wday] } 12 | end 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /lib/rules/parameters/parameter.rb: -------------------------------------------------------------------------------- 1 | module Rules::Parameters 2 | class Parameter 3 | VALID_TYPES = [:date, :integer, :float, :boolean, :string, :regexp] 4 | 5 | attr_accessor :name, :type, :key 6 | 7 | def self.cast(value, type) 8 | return value unless type 9 | case type 10 | when :date 11 | Date.parse(value.to_s) 12 | when :integer 13 | value.to_i 14 | when :float 15 | value.to_f 16 | when :boolean 17 | value.to_s == 'true' ? true : false 18 | when :string 19 | value.to_s 20 | when :regexp 21 | Regexp.new(value.to_s) 22 | else 23 | raise "Don't know how to cast #{type}" 24 | end 25 | end 26 | 27 | def initialize(options = {}) 28 | self.key = options[:key].to_sym 29 | self.name = options[:name] || options[:key].to_s.humanize 30 | self.type = options[:type] if options[:type] 31 | 32 | raise "Unknown type #{type}" if type && !VALID_TYPES.include?(type) 33 | end 34 | 35 | def to_s 36 | name 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /lib/rules/rule.rb: -------------------------------------------------------------------------------- 1 | require 'rules/evaluators' 2 | require 'rules/parameters' 3 | 4 | module Rules 5 | class Rule < ActiveRecord::Base 6 | belongs_to :rule_set, class_name: 'Rules::RuleSet' 7 | 8 | validates :evaluator_key, presence: true, inclusion: {in: Evaluators.list.keys.map(&:to_s)} 9 | validates :lhs_parameter_key, parameter_key: true 10 | validates :rhs_parameter_key, parameter_key: true, if: :rhs_parameter_key 11 | validates :rhs_parameter_key, presence: true, if: :requires_rhs?, unless: :rhs_parameter_raw 12 | validates :rhs_parameter_key, absence: true, unless: :requires_rhs? 13 | validates :rhs_parameter_raw, absence: true, unless: :requires_rhs? 14 | validates :rhs_parameter_key, absence: true, if: :rhs_parameter_raw 15 | 16 | store :expression, :accessors => [:evaluator_key, :lhs_parameter_key, :rhs_parameter_key, :rhs_parameter_raw] 17 | 18 | def evaluate(attributes = {}) 19 | lhv = lhs_parameter_value(attributes) 20 | rhv = rhs_parameter_value(attributes) if evaluator.requires_rhs? 21 | evaluator.evaluate(lhv, rhv) 22 | end 23 | 24 | def evaluator 25 | @evaluator ||= evaluator_key ? Evaluators.list[evaluator_key.to_sym] : nil 26 | end 27 | 28 | def lhs_parameter_key 29 | key_from_store :lhs_parameter_key 30 | end 31 | 32 | def rhs_parameter_key 33 | key_from_store :rhs_parameter_key 34 | end 35 | 36 | def evaluator_key 37 | key_from_store :evaluator_key 38 | end 39 | 40 | def lhs_parameter_value(attributes = {}) 41 | lhs_parameter.try(:evaluate, attributes) 42 | end 43 | 44 | def rhs_parameter_value(attributes = {}) 45 | if rhs_parameter.respond_to?(:evaluate) 46 | rhs_parameter.try(:evaluate, attributes) 47 | else 48 | rhv = Parameters::Parameter.cast(rhs_parameter_raw, lhs_parameter.try(:type)) 49 | Parameters::Parameter.cast(rhv, evaluator.try(:type_for_rhs)) 50 | end 51 | end 52 | 53 | def rhs_parameter 54 | rhs_parameter_key ? parameter_from_key(rhs_parameter_key) : rhs_parameter_raw 55 | end 56 | 57 | def lhs_parameter 58 | @lhs_parameter ||= lhs_parameter_key ? parameter_from_key(lhs_parameter_key) : nil 59 | end 60 | 61 | def valid_parameter_keys 62 | Parameters.constants.keys.map(&:to_s) + valid_attributes.keys.map(&:to_s) 63 | end 64 | 65 | def valid_attributes 66 | rule_set ? rule_set.attributes : {} 67 | end 68 | 69 | def requires_rhs? 70 | evaluator ? evaluator.requires_rhs? : false 71 | end 72 | 73 | def rule_set 74 | super || ObjectSpace.each_object(RuleSet).detect { |rs| rs.rules.include?(self) } 75 | end 76 | 77 | private 78 | 79 | def key_from_store(key) 80 | expression[key].blank? ? nil : expression[key] 81 | end 82 | 83 | def parameter_from_key(key) 84 | Parameters.constants[key.to_sym] || valid_attributes[key.to_sym] 85 | end 86 | end 87 | end 88 | -------------------------------------------------------------------------------- /lib/rules/rule_set.rb: -------------------------------------------------------------------------------- 1 | require 'rules/has_rules' 2 | require 'rules/parameters/attribute' 3 | 4 | module Rules 5 | class RuleSet < ActiveRecord::Base 6 | belongs_to :source, polymorphic: true 7 | 8 | has_many :rules, class_name: 'Rules::Rule' 9 | 10 | accepts_nested_attributes_for :rules, allow_destroy: true 11 | 12 | validates_inclusion_of :evaluation_logic, in: %w(all any), allow_nil: true, allow_blank: true 13 | 14 | @@attributes = Hash.new({}) 15 | 16 | def self.set_attributes_for(klass, klass_attributes) 17 | @@attributes[klass] = @@attributes[klass].merge(attributize(klass_attributes)) 18 | end 19 | 20 | def self.attributes 21 | @@attributes 22 | end 23 | 24 | def self.attributize(attributes_hash) 25 | mapped_hash = {} 26 | attributes_hash.each do |k, v| 27 | mapped_hash[k] = Rules::Parameters::Attribute.new(v.merge(key: k)) 28 | end 29 | mapped_hash 30 | end 31 | 32 | def attributes 33 | source_klass = source ? source.class : source_type.try(:constantize) 34 | return {} unless source_klass 35 | self.class.attributes[source_klass] 36 | end 37 | 38 | # TODO: Arbitrary rule set logic (Treetop) 39 | def evaluate(attributes = {}) 40 | return true unless rules.any? 41 | if evaluation_logic == 'any' 42 | !!rules.detect { |rule| rule.evaluate(attributes) } 43 | else 44 | rules.each do |rule| 45 | return false unless rule.evaluate(attributes) 46 | end 47 | true 48 | end 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /lib/rules/version.rb: -------------------------------------------------------------------------------- 1 | module Rules 2 | VERSION = '1.1.1' 3 | end 4 | -------------------------------------------------------------------------------- /lib/tasks/rules_tasks.rake: -------------------------------------------------------------------------------- 1 | # desc "Explaining what the task does" 2 | # task :rules do 3 | # # Task goes here 4 | # end 5 | -------------------------------------------------------------------------------- /rules.gemspec: -------------------------------------------------------------------------------- 1 | $:.push File.expand_path("../lib", __FILE__) 2 | 3 | # Maintain your gem's version: 4 | require "rules/version" 5 | 6 | # Describe your gem and declare its dependencies: 7 | Gem::Specification.new do |s| 8 | s.name = "rules" 9 | s.version = Rules::VERSION 10 | s.authors = ["Anthony Zacharakis"] 11 | s.email = ["anthony@lumoslabs.com"] 12 | s.homepage = "https://github.com/azach/rules" 13 | s.summary = "Rules engine that allows you to add customizable business rules to any ActiveRecord model." 14 | s.description = "Rules engine that allows you to add customizable business rules to any ActiveRecord model." 15 | 16 | s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] 17 | s.test_files = Dir["spec/**/*"] 18 | 19 | s.add_dependency 'activeresource' 20 | s.add_dependency "rails" 21 | 22 | s.add_development_dependency "sqlite3" 23 | s.add_development_dependency "rspec-rails" 24 | s.add_development_dependency 'rspec-collection_matchers' 25 | end 26 | -------------------------------------------------------------------------------- /spec/dummy/README.rdoc: -------------------------------------------------------------------------------- 1 | == Welcome to Rails 2 | 3 | Rails is a web-application framework that includes everything needed to create 4 | database-backed web applications according to the Model-View-Control pattern. 5 | 6 | This pattern splits the view (also called the presentation) into "dumb" 7 | templates that are primarily responsible for inserting pre-built data in between 8 | HTML tags. The model contains the "smart" domain objects (such as Account, 9 | Product, Person, Post) that holds all the business logic and knows how to 10 | persist themselves to a database. The controller handles the incoming requests 11 | (such as Save New Account, Update Product, Show Post) by manipulating the model 12 | and directing data to the view. 13 | 14 | In Rails, the model is handled by what's called an object-relational mapping 15 | layer entitled Active Record. This layer allows you to present the data from 16 | database rows as objects and embellish these data objects with business logic 17 | methods. You can read more about Active Record in 18 | link:files/vendor/rails/activerecord/README.html. 19 | 20 | The controller and view are handled by the Action Pack, which handles both 21 | layers by its two parts: Action View and Action Controller. These two layers 22 | are bundled in a single package due to their heavy interdependence. This is 23 | unlike the relationship between the Active Record and Action Pack that is much 24 | more separate. Each of these packages can be used independently outside of 25 | Rails. You can read more about Action Pack in 26 | link:files/vendor/rails/actionpack/README.html. 27 | 28 | 29 | == Getting Started 30 | 31 | 1. At the command prompt, create a new Rails application: 32 | rails new myapp (where myapp is the application name) 33 | 34 | 2. Change directory to myapp and start the web server: 35 | cd myapp; rails server (run with --help for options) 36 | 37 | 3. Go to http://localhost:3000/ and you'll see: 38 | "Welcome aboard: You're riding Ruby on Rails!" 39 | 40 | 4. Follow the guidelines to start developing your application. You can find 41 | the following resources handy: 42 | 43 | * The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html 44 | * Ruby on Rails Tutorial Book: http://www.railstutorial.org/ 45 | 46 | 47 | == Debugging Rails 48 | 49 | Sometimes your application goes wrong. Fortunately there are a lot of tools that 50 | will help you debug it and get it back on the rails. 51 | 52 | First area to check is the application log files. Have "tail -f" commands 53 | running on the server.log and development.log. Rails will automatically display 54 | debugging and runtime information to these files. Debugging info will also be 55 | shown in the browser on requests from 127.0.0.1. 56 | 57 | You can also log your own messages directly into the log file from your code 58 | using the Ruby logger class from inside your controllers. Example: 59 | 60 | class WeblogController < ActionController::Base 61 | def destroy 62 | @weblog = Weblog.find(params[:id]) 63 | @weblog.destroy 64 | logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!") 65 | end 66 | end 67 | 68 | The result will be a message in your log file along the lines of: 69 | 70 | Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1! 71 | 72 | More information on how to use the logger is at http://www.ruby-doc.org/core/ 73 | 74 | Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are 75 | several books available online as well: 76 | 77 | * Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe) 78 | * Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide) 79 | 80 | These two books will bring you up to speed on the Ruby language and also on 81 | programming in general. 82 | 83 | 84 | == Debugger 85 | 86 | Debugger support is available through the debugger command when you start your 87 | Mongrel or WEBrick server with --debugger. This means that you can break out of 88 | execution at any point in the code, investigate and change the model, and then, 89 | resume execution! You need to install ruby-debug to run the server in debugging 90 | mode. With gems, use sudo gem install ruby-debug. Example: 91 | 92 | class WeblogController < ActionController::Base 93 | def index 94 | @posts = Post.all 95 | debugger 96 | end 97 | end 98 | 99 | So the controller will accept the action, run the first line, then present you 100 | with a IRB prompt in the server window. Here you can do things like: 101 | 102 | >> @posts.inspect 103 | => "[#nil, "body"=>nil, "id"=>"1"}>, 105 | #"Rails", "body"=>"Only ten..", "id"=>"2"}>]" 107 | >> @posts.first.title = "hello from a debugger" 108 | => "hello from a debugger" 109 | 110 | ...and even better, you can examine how your runtime objects actually work: 111 | 112 | >> f = @posts.first 113 | => #nil, "body"=>nil, "id"=>"1"}> 114 | >> f. 115 | Display all 152 possibilities? (y or n) 116 | 117 | Finally, when you're ready to resume execution, you can enter "cont". 118 | 119 | 120 | == Console 121 | 122 | The console is a Ruby shell, which allows you to interact with your 123 | application's domain model. Here you'll have all parts of the application 124 | configured, just like it is when the application is running. You can inspect 125 | domain models, change values, and save to the database. Starting the script 126 | without arguments will launch it in the development environment. 127 | 128 | To start the console, run rails console from the application 129 | directory. 130 | 131 | Options: 132 | 133 | * Passing the -s, --sandbox argument will rollback any modifications 134 | made to the database. 135 | * Passing an environment name as an argument will load the corresponding 136 | environment. Example: rails console production. 137 | 138 | To reload your controllers and models after launching the console run 139 | reload! 140 | 141 | More information about irb can be found at: 142 | link:http://www.rubycentral.org/pickaxe/irb.html 143 | 144 | 145 | == dbconsole 146 | 147 | You can go to the command line of your database directly through rails 148 | dbconsole. You would be connected to the database with the credentials 149 | defined in database.yml. Starting the script without arguments will connect you 150 | to the development database. Passing an argument will connect you to a different 151 | database, like rails dbconsole production. Currently works for MySQL, 152 | PostgreSQL and SQLite 3. 153 | 154 | == Description of Contents 155 | 156 | The default directory structure of a generated Ruby on Rails application: 157 | 158 | |-- app 159 | | |-- assets 160 | | |-- images 161 | | |-- javascripts 162 | | `-- stylesheets 163 | | |-- controllers 164 | | |-- helpers 165 | | |-- mailers 166 | | |-- models 167 | | `-- views 168 | | `-- layouts 169 | |-- config 170 | | |-- environments 171 | | |-- initializers 172 | | `-- locales 173 | |-- db 174 | |-- doc 175 | |-- lib 176 | | `-- tasks 177 | |-- log 178 | |-- public 179 | |-- script 180 | |-- test 181 | | |-- fixtures 182 | | |-- functional 183 | | |-- integration 184 | | |-- performance 185 | | `-- unit 186 | |-- tmp 187 | | |-- cache 188 | | |-- pids 189 | | |-- sessions 190 | | `-- sockets 191 | `-- vendor 192 | |-- assets 193 | `-- stylesheets 194 | `-- plugins 195 | 196 | app 197 | Holds all the code that's specific to this particular application. 198 | 199 | app/assets 200 | Contains subdirectories for images, stylesheets, and JavaScript files. 201 | 202 | app/controllers 203 | Holds controllers that should be named like weblogs_controller.rb for 204 | automated URL mapping. All controllers should descend from 205 | ApplicationController which itself descends from ActionController::Base. 206 | 207 | app/models 208 | Holds models that should be named like post.rb. Models descend from 209 | ActiveRecord::Base by default. 210 | 211 | app/views 212 | Holds the template files for the view that should be named like 213 | weblogs/index.html.erb for the WeblogsController#index action. All views use 214 | eRuby syntax by default. 215 | 216 | app/views/layouts 217 | Holds the template files for layouts to be used with views. This models the 218 | common header/footer method of wrapping views. In your views, define a layout 219 | using the layout :default and create a file named default.html.erb. 220 | Inside default.html.erb, call <% yield %> to render the view using this 221 | layout. 222 | 223 | app/helpers 224 | Holds view helpers that should be named like weblogs_helper.rb. These are 225 | generated for you automatically when using generators for controllers. 226 | Helpers can be used to wrap functionality for your views into methods. 227 | 228 | config 229 | Configuration files for the Rails environment, the routing map, the database, 230 | and other dependencies. 231 | 232 | db 233 | Contains the database schema in schema.rb. db/migrate contains all the 234 | sequence of Migrations for your schema. 235 | 236 | doc 237 | This directory is where your application documentation will be stored when 238 | generated using rake doc:app 239 | 240 | lib 241 | Application specific libraries. Basically, any kind of custom code that 242 | doesn't belong under controllers, models, or helpers. This directory is in 243 | the load path. 244 | 245 | public 246 | The directory available for the web server. Also contains the dispatchers and the 247 | default HTML files. This should be set as the DOCUMENT_ROOT of your web 248 | server. 249 | 250 | script 251 | Helper scripts for automation and generation. 252 | 253 | test 254 | Unit and functional tests along with fixtures. When using the rails generate 255 | command, template test files will be generated for you and placed in this 256 | directory. 257 | 258 | vendor 259 | External libraries that the application depends on. Also includes the plugins 260 | subdirectory. If the app has frozen rails, those gems also go here, under 261 | vendor/rails/. This directory is in the load path. 262 | -------------------------------------------------------------------------------- /spec/dummy/Rakefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env rake 2 | # Add your own tasks in files placed in lib/tasks ending in .rake, 3 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 4 | 5 | require File.expand_path('../config/application', __FILE__) 6 | 7 | Dummy::Application.load_tasks 8 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/dashboards.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register_page "Dashboard" do 2 | 3 | menu :priority => 1, :label => proc{ I18n.t("active_admin.dashboard") } 4 | 5 | content :title => proc{ I18n.t("active_admin.dashboard") } do 6 | div :class => "blank_slate_container", :id => "dashboard_default_message" do 7 | span :class => "blank_slate" do 8 | span "Welcome to Active Admin. This is the default dashboard page." 9 | small "To add dashboard sections, checkout 'app/admin/dashboards.rb'" 10 | end 11 | end 12 | 13 | # Here is an example of a simple dashboard with columns and panels. 14 | # 15 | # columns do 16 | # column do 17 | # panel "Recent Posts" do 18 | # ul do 19 | # Post.recent(5).map do |post| 20 | # li link_to(post.title, admin_post_path(post)) 21 | # end 22 | # end 23 | # end 24 | # end 25 | 26 | # column do 27 | # panel "Info" do 28 | # para "Welcome to ActiveAdmin." 29 | # end 30 | # end 31 | # end 32 | end # content 33 | end 34 | -------------------------------------------------------------------------------- /spec/dummy/app/admin/orders.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.register Order do 2 | show do |f| 3 | attributes_table do 4 | row :id 5 | row :quantity 6 | row :price 7 | row :customer 8 | row :placed 9 | row :shipped 10 | row :created_at 11 | row :updated_at 12 | end 13 | 14 | show_rules 15 | end 16 | 17 | form do |f| 18 | f.inputs 'Details' do 19 | f.input :quantity 20 | f.input :price 21 | f.input :customer 22 | f.input :placed 23 | f.input :shipped 24 | end 25 | 26 | f.has_rules 27 | 28 | f.buttons 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/images/edit_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/app/assets/images/edit_example.png -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/active_admin.js: -------------------------------------------------------------------------------- 1 | //= require active_admin/base 2 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // This is a manifest file that'll be compiled into application.js, which will include all the files 2 | // listed below. 3 | // 4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, 5 | // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. 6 | // 7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8 | // the compiled file. 9 | // 10 | // WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD 11 | // GO AFTER THE REQUIRES BELOW. 12 | // 13 | //= require jquery 14 | //= require jquery_ujs 15 | //= require_tree . 16 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/active_admin.css.scss: -------------------------------------------------------------------------------- 1 | // SASS variable overrides must be declared before loading up Active Admin's styles. 2 | // 3 | // To view the variables that Active Admin provides, take a look at 4 | // `app/assets/stylesheets/active_admin/mixins/_variables.css.scss` in the 5 | // Active Admin source. 6 | // 7 | // For example, to change the sidebar width: 8 | // $sidebar-width: 242px; 9 | 10 | // Active Admin's got SASS! 11 | @import "active_admin/mixins"; 12 | @import "active_admin/base"; 13 | 14 | // Overriding any non-variable SASS must be done after the fact. 15 | // For example, to change the default status-tag color: 16 | // 17 | // body.active_admin { 18 | // .status_tag { background: #6090DB; } 19 | // } 20 | // 21 | // Notice that Active Admin CSS rules are nested within a 22 | // 'body.active_admin' selector to prevent conflicts with 23 | // other pages in the app. It is best to wrap your changes in a 24 | // namespace so they are properly recognized. You have options 25 | // if you e.g. want different styles for different namespaces: 26 | // 27 | // .active_admin applies to any Active Admin namespace 28 | // .admin_namespace applies to the admin namespace (eg: /admin) 29 | // .other_namespace applies to a custom namespace named other (eg: /other) 30 | -------------------------------------------------------------------------------- /spec/dummy/app/assets/stylesheets/application.css: -------------------------------------------------------------------------------- 1 | /* 2 | * This is a manifest file that'll be compiled into application.css, which will include all the files 3 | * listed below. 4 | * 5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, 6 | * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. 7 | * 8 | * You're free to add application-wide styles to this file and they'll appear at the top of the 9 | * compiled file, but it's generally better to create a new file per style scope. 10 | * 11 | *= require_self 12 | *= require_tree . 13 | */ 14 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | protect_from_forgery 3 | end 4 | -------------------------------------------------------------------------------- /spec/dummy/app/controllers/orders_controller.rb: -------------------------------------------------------------------------------- 1 | class OrdersController < ApplicationController 2 | def show 3 | @order = Order.last || Order.create! 4 | end 5 | 6 | def create 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /spec/dummy/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/dummy/app/mailers/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/app/mailers/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/app/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/app/models/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/app/models/admin_user.rb: -------------------------------------------------------------------------------- 1 | class AdminUser < ActiveRecord::Base 2 | # Include default devise modules. Others available are: 3 | # :token_authenticatable, :confirmable, 4 | # :lockable, :timeoutable and :omniauthable 5 | devise :database_authenticatable, 6 | :recoverable, :rememberable, :trackable, :validatable 7 | end 8 | -------------------------------------------------------------------------------- /spec/dummy/app/models/order.rb: -------------------------------------------------------------------------------- 1 | class Order < ActiveRecord::Base 2 | include Rules::HasRules 3 | 4 | has_rule_attributes({ 5 | customer_email: { 6 | name: 'customer email address' 7 | }, 8 | order_price: { 9 | name: 'order price' 10 | } 11 | }) 12 | 13 | def check_if_valid 14 | evaluate \ 15 | customer: customer, 16 | price: price 17 | end 18 | end 19 | -------------------------------------------------------------------------------- /spec/dummy/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dummy 5 | <%= stylesheet_link_tag "application", :media => "all" %> 6 | <%= javascript_include_tag "application" %> 7 | <%= csrf_meta_tags %> 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /spec/dummy/app/views/orders/show.html.haml: -------------------------------------------------------------------------------- 1 | = form_for @order do |f| 2 | = rules_for @order.rule_set -------------------------------------------------------------------------------- /spec/dummy/bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) 3 | load Gem.bin_path('bundler', 'bundle') 4 | -------------------------------------------------------------------------------- /spec/dummy/bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | APP_PATH = File.expand_path('../../config/application', __FILE__) 3 | require_relative '../config/boot' 4 | require 'rails/commands' 5 | -------------------------------------------------------------------------------- /spec/dummy/bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require_relative '../config/boot' 3 | require 'rake' 4 | Rake.application.run 5 | -------------------------------------------------------------------------------- /spec/dummy/bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require 'pathname' 3 | 4 | # path to your application root. 5 | APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) 6 | 7 | Dir.chdir APP_ROOT do 8 | # This script is a starting point to setup your application. 9 | # Add necessary setup steps to this file: 10 | 11 | puts "== Installing dependencies ==" 12 | system "gem install bundler --conservative" 13 | system "bundle check || bundle install" 14 | 15 | # puts "\n== Copying sample files ==" 16 | # unless File.exist?("config/database.yml") 17 | # system "cp config/database.yml.sample config/database.yml" 18 | # end 19 | 20 | puts "\n== Preparing database ==" 21 | system "bin/rake db:setup" 22 | 23 | puts "\n== Removing old logs and tempfiles ==" 24 | system "rm -f log/*" 25 | system "rm -rf tmp/cache" 26 | 27 | puts "\n== Restarting application server ==" 28 | system "touch tmp/restart.txt" 29 | end 30 | -------------------------------------------------------------------------------- /spec/dummy/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run Dummy::Application 5 | -------------------------------------------------------------------------------- /spec/dummy/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require 'rails/all' 4 | 5 | # Require the gems listed in Gemfile, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(*Rails.groups) 8 | 9 | module Dummy 10 | class Application < Rails::Application 11 | # Settings in config/environments/* take precedence over those specified here. 12 | # Application configuration should go into files in config/initializers 13 | # -- all .rb files in that directory are automatically loaded. 14 | 15 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 16 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 17 | # config.time_zone = 'Central Time (US & Canada)' 18 | 19 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 20 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 21 | # config.i18n.default_locale = :de 22 | 23 | # Do not swallow errors in after_commit/after_rollback callbacks. 24 | # config.active_record.raise_in_transactional_callbacks = true 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /spec/dummy/config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) 2 | 3 | require 'bundler/setup' # Set up gems listed in the Gemfile. 4 | $:.unshift File.expand_path('../../../../lib', __FILE__) 5 | -------------------------------------------------------------------------------- /spec/dummy/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3 3 | # 4 | # Ensure the SQLite 3 gem is defined in your Gemfile 5 | # gem 'sqlite3' 6 | development: 7 | adapter: sqlite3 8 | database: db/development.sqlite3 9 | pool: 5 10 | timeout: 5000 11 | 12 | # Warning: The database defined as "test" will be erased and 13 | # re-generated from your development database when you run "rake". 14 | # Do not set this db to the same as development or production. 15 | test: 16 | adapter: sqlite3 17 | database: db/test.sqlite3 18 | pool: 5 19 | timeout: 5000 20 | 21 | production: 22 | adapter: sqlite3 23 | database: db/production.sqlite3 24 | pool: 5 25 | timeout: 5000 26 | -------------------------------------------------------------------------------- /spec/dummy/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the Rails application. 5 | Dummy::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the web server when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching. 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send. 17 | config.action_mailer.raise_delivery_errors = false 18 | 19 | # Print deprecation notices to the Rails logger. 20 | config.active_support.deprecation = :log 21 | 22 | # Raise an error on page load if there are pending migrations. 23 | config.active_record.migration_error = :page_load 24 | 25 | # Debug mode disables concatenation and preprocessing of assets. 26 | # This option may cause significant delays in view rendering with a large 27 | # number of complex assets. 28 | config.assets.debug = true 29 | 30 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 31 | # yet still be able to expire them through the digest params. 32 | config.assets.digest = true 33 | 34 | # Adds additional error checking when serving assets at runtime. 35 | # Checks for improperly declared sprockets dependencies. 36 | # Raises helpful error messages. 37 | config.assets.raise_runtime_errors = true 38 | 39 | # Raises error for missing translations 40 | # config.action_view.raise_on_missing_translations = true 41 | end 42 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb 3 | 4 | # Code is not reloaded between requests. 5 | config.cache_classes = true 6 | 7 | # Eager load code on boot. This eager loads most of Rails and 8 | # your application in memory, allowing both threaded web servers 9 | # and those relying on copy on write to perform better. 10 | # Rake tasks automatically ignore this option for performance. 11 | config.eager_load = true 12 | 13 | # Full error reports are disabled and caching is turned on. 14 | config.consider_all_requests_local = false 15 | config.action_controller.perform_caching = true 16 | 17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application 18 | # Add `rack-cache` to your Gemfile before enabling this. 19 | # For large-scale production use, consider using a caching reverse proxy like 20 | # NGINX, varnish or squid. 21 | # config.action_dispatch.rack_cache = true 22 | 23 | # Disable serving static files from the `/public` folder by default since 24 | # Apache or NGINX already handles this. 25 | config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 26 | 27 | # Compress JavaScripts and CSS. 28 | config.assets.js_compressor = :uglifier 29 | # config.assets.css_compressor = :sass 30 | 31 | # Do not fallback to assets pipeline if a precompiled asset is missed. 32 | config.assets.compile = false 33 | 34 | # Asset digests allow you to set far-future HTTP expiration dates on all assets, 35 | # yet still be able to expire them through the digest params. 36 | config.assets.digest = true 37 | 38 | # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb 39 | 40 | # Specifies the header that your server uses for sending files. 41 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 42 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 43 | 44 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 45 | # config.force_ssl = true 46 | 47 | # Use the lowest log level to ensure availability of diagnostic information 48 | # when problems arise. 49 | config.log_level = :debug 50 | 51 | # Prepend all log lines with the following tags. 52 | # config.log_tags = [ :subdomain, :uuid ] 53 | 54 | # Use a different logger for distributed setups. 55 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) 56 | 57 | # Use a different cache store in production. 58 | # config.cache_store = :mem_cache_store 59 | 60 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 61 | # config.action_controller.asset_host = 'http://assets.example.com' 62 | 63 | # Ignore bad email addresses and do not raise email delivery errors. 64 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 65 | # config.action_mailer.raise_delivery_errors = false 66 | 67 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 68 | # the I18n.default_locale when a translation cannot be found). 69 | config.i18n.fallbacks = true 70 | 71 | # Send deprecation notices to registered listeners. 72 | config.active_support.deprecation = :notify 73 | 74 | # Use default logging formatter so that PID and timestamp are not suppressed. 75 | config.log_formatter = ::Logger::Formatter.new 76 | 77 | # Do not dump schema after migrations. 78 | config.active_record.dump_schema_after_migration = false 79 | end 80 | -------------------------------------------------------------------------------- /spec/dummy/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.configure do 2 | # Settings specified here will take precedence over those in config/application.rb. 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. This avoids loading your whole application 11 | # just for the purpose of running a single test. If you are using a tool that 12 | # preloads Rails for running tests, you may have to set it to true. 13 | config.eager_load = false 14 | 15 | # Configure static file server for tests with Cache-Control for performance. 16 | config.serve_static_files = true 17 | config.static_cache_control = 'public, max-age=3600' 18 | 19 | # Show full error reports and disable caching. 20 | config.consider_all_requests_local = true 21 | config.action_controller.perform_caching = false 22 | 23 | # Raise exceptions instead of rendering exception templates. 24 | config.action_dispatch.show_exceptions = false 25 | 26 | # Disable request forgery protection in test environment. 27 | config.action_controller.allow_forgery_protection = false 28 | 29 | # Tell Action Mailer not to deliver emails to the real world. 30 | # The :test delivery method accumulates sent emails in the 31 | # ActionMailer::Base.deliveries array. 32 | config.action_mailer.delivery_method = :test 33 | 34 | # Randomize the order test cases are executed. 35 | config.active_support.test_order = :random 36 | 37 | # Print deprecation notices to the stderr. 38 | config.active_support.deprecation = :stderr 39 | 40 | # Raises error for missing translations 41 | # config.action_view.raise_on_missing_translations = true 42 | end 43 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/active_admin.rb: -------------------------------------------------------------------------------- 1 | ActiveAdmin.setup do |config| 2 | 3 | # == Site Title 4 | # 5 | # Set the title that is displayed on the main layout 6 | # for each of the active admin pages. 7 | # 8 | config.site_title = "Dummy" 9 | 10 | # Set the link url for the title. For example, to take 11 | # users to your main site. Defaults to no link. 12 | # 13 | # config.site_title_link = "/" 14 | 15 | # Set an optional image to be displayed for the header 16 | # instead of a string (overrides :site_title) 17 | # 18 | # Note: Recommended image height is 21px to properly fit in the header 19 | # 20 | # config.site_title_image = "/images/logo.png" 21 | 22 | # == Default Namespace 23 | # 24 | # Set the default namespace each administration resource 25 | # will be added to. 26 | # 27 | # eg: 28 | # config.default_namespace = :hello_world 29 | # 30 | # This will create resources in the HelloWorld module and 31 | # will namespace routes to /hello_world/* 32 | # 33 | # To set no namespace by default, use: 34 | # config.default_namespace = false 35 | # 36 | # Default: 37 | # config.default_namespace = :admin 38 | # 39 | # You can customize the settings for each namespace by using 40 | # a namespace block. For example, to change the site title 41 | # within a namespace: 42 | # 43 | # config.namespace :admin do |admin| 44 | # admin.site_title = "Custom Admin Title" 45 | # end 46 | # 47 | # This will ONLY change the title for the admin section. Other 48 | # namespaces will continue to use the main "site_title" configuration. 49 | 50 | # == User Authentication 51 | # 52 | # Active Admin will automatically call an authentication 53 | # method in a before filter of all controller actions to 54 | # ensure that there is a currently logged in admin user. 55 | # 56 | # This setting changes the method which Active Admin calls 57 | # within the controller. 58 | config.authentication_method = :authenticate_admin_user! 59 | 60 | 61 | # == Current User 62 | # 63 | # Active Admin will associate actions with the current 64 | # user performing them. 65 | # 66 | # This setting changes the method which Active Admin calls 67 | # to return the currently logged in user. 68 | config.current_user_method = :current_admin_user 69 | 70 | 71 | # == Logging Out 72 | # 73 | # Active Admin displays a logout link on each screen. These 74 | # settings configure the location and method used for the link. 75 | # 76 | # This setting changes the path where the link points to. If it's 77 | # a string, the strings is used as the path. If it's a Symbol, we 78 | # will call the method to return the path. 79 | # 80 | # Default: 81 | config.logout_link_path = :destroy_admin_user_session_path 82 | 83 | # This setting changes the http method used when rendering the 84 | # link. For example :get, :delete, :put, etc.. 85 | # 86 | # Default: 87 | # config.logout_link_method = :get 88 | 89 | # == Root 90 | # 91 | # Set the action to call for the root path. You can set different 92 | # roots for each namespace. 93 | # 94 | # Default: 95 | # config.root_to = 'dashboard#index' 96 | 97 | # == Admin Comments 98 | # 99 | # Admin comments allow you to add comments to any model for admin use. 100 | # Admin comments are enabled by default. 101 | # 102 | # Default: 103 | # config.allow_comments = true 104 | # 105 | # You can turn them on and off for any given namespace by using a 106 | # namespace config block. 107 | # 108 | # Eg: 109 | # config.namespace :without_comments do |without_comments| 110 | # without_comments.allow_comments = false 111 | # end 112 | 113 | 114 | # == Batch Actions 115 | # 116 | # Enable and disable Batch Actions 117 | # 118 | config.batch_actions = true 119 | 120 | 121 | # == Controller Filters 122 | # 123 | # You can add before, after and around filters to all of your 124 | # Active Admin resources from here. 125 | # 126 | # config.before_filter :do_something_awesome 127 | 128 | 129 | # == Register Stylesheets & Javascripts 130 | # 131 | # We recommend using the built in Active Admin layout and loading 132 | # up your own stylesheets / javascripts to customize the look 133 | # and feel. 134 | # 135 | # To load a stylesheet: 136 | # config.register_stylesheet 'my_stylesheet.css' 137 | 138 | # You can provide an options hash for more control, which is passed along to stylesheet_link_tag(): 139 | # config.register_stylesheet 'my_print_stylesheet.css', :media => :print 140 | # 141 | # To load a javascript file: 142 | # config.register_javascript 'my_javascript.js' 143 | 144 | 145 | # == CSV options 146 | # 147 | # Set the CSV builder separator (default is ",") 148 | # config.csv_column_separator = ',' 149 | end 150 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/assets.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Version of your assets, change this if you want to expire all your assets. 4 | Rails.application.config.assets.version = '1.0' 5 | 6 | # Add additional assets to the asset load path 7 | # Rails.application.config.assets.paths << Emoji.images_path 8 | 9 | # Precompile additional assets. 10 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. 11 | # Rails.application.config.assets.precompile += %w( search.js ) 12 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/cookies_serializer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.action_dispatch.cookies_serializer = :marshal 4 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. 2 | # Many of these configuration options can be set straight in your model. 3 | Devise.setup do |config| 4 | # ==> Mailer Configuration 5 | # Configure the e-mail address which will be shown in Devise::Mailer, 6 | # note that it will be overwritten if you use your own mailer class with default "from" parameter. 7 | config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com" 8 | 9 | # Configure the class responsible to send e-mails. 10 | # config.mailer = "Devise::Mailer" 11 | 12 | # ==> ORM configuration 13 | # Load and configure the ORM. Supports :active_record (default) and 14 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 15 | # available as additional gems. 16 | require 'devise/orm/active_record' 17 | 18 | # ==> Configuration for any authentication mechanism 19 | # Configure which keys are used when authenticating a user. The default is 20 | # just :email. You can configure it to use [:username, :subdomain], so for 21 | # authenticating a user, both parameters are required. Remember that those 22 | # parameters are used only when authenticating and not when retrieving from 23 | # session. If you need permissions, you should implement that in a before filter. 24 | # You can also supply a hash where the value is a boolean determining whether 25 | # or not authentication should be aborted when the value is not present. 26 | # config.authentication_keys = [ :email ] 27 | 28 | # Configure parameters from the request object used for authentication. Each entry 29 | # given should be a request method and it will automatically be passed to the 30 | # find_for_authentication method and considered in your model lookup. For instance, 31 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 32 | # The same considerations mentioned for authentication_keys also apply to request_keys. 33 | # config.request_keys = [] 34 | 35 | # Configure which authentication keys should be case-insensitive. 36 | # These keys will be downcased upon creating or modifying a user and when used 37 | # to authenticate or find a user. Default is :email. 38 | config.case_insensitive_keys = [ :email ] 39 | 40 | # Configure which authentication keys should have whitespace stripped. 41 | # These keys will have whitespace before and after removed upon creating or 42 | # modifying a user and when used to authenticate or find a user. Default is :email. 43 | config.strip_whitespace_keys = [ :email ] 44 | 45 | # Tell if authentication through request.params is enabled. True by default. 46 | # It can be set to an array that will enable params authentication only for the 47 | # given strategies, for example, `config.params_authenticatable = [:database]` will 48 | # enable it only for database (email + password) authentication. 49 | # config.params_authenticatable = true 50 | 51 | # Tell if authentication through HTTP Basic Auth is enabled. False by default. 52 | # It can be set to an array that will enable http authentication only for the 53 | # given strategies, for example, `config.http_authenticatable = [:token]` will 54 | # enable it only for token authentication. 55 | # config.http_authenticatable = false 56 | 57 | # If http headers should be returned for AJAX requests. True by default. 58 | # config.http_authenticatable_on_xhr = true 59 | 60 | # The realm used in Http Basic Authentication. "Application" by default. 61 | # config.http_authentication_realm = "Application" 62 | 63 | # It will change confirmation, password recovery and other workflows 64 | # to behave the same regardless if the e-mail provided was right or wrong. 65 | # Does not affect registerable. 66 | # config.paranoid = true 67 | 68 | # By default Devise will store the user in session. You can skip storage for 69 | # :http_auth and :token_auth by adding those symbols to the array below. 70 | # Notice that if you are skipping storage for all authentication paths, you 71 | # may want to disable generating routes to Devise's sessions controller by 72 | # passing :skip => :sessions to `devise_for` in your config/routes.rb 73 | config.skip_session_storage = [:http_auth] 74 | 75 | # ==> Configuration for :database_authenticatable 76 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If 77 | # using other encryptors, it sets how many times you want the password re-encrypted. 78 | # 79 | # Limiting the stretches to just one in testing will increase the performance of 80 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 81 | # a value less than 10 in other environments. 82 | config.stretches = Rails.env.test? ? 1 : 10 83 | 84 | # Setup a pepper to generate the encrypted password. 85 | # config.pepper = "61487404d51ea5b61e67512bf38b6380d2339d0e53cf84135114f7066c48a6d70d8ba7e147e6d25b951f1bf6913f34dfab1e90b6da5d4cda7fc0a3fa5318b53f" 86 | 87 | # ==> Configuration for :confirmable 88 | # A period that the user is allowed to access the website even without 89 | # confirming his account. For instance, if set to 2.days, the user will be 90 | # able to access the website for two days without confirming his account, 91 | # access will be blocked just in the third day. Default is 0.days, meaning 92 | # the user cannot access the website without confirming his account. 93 | # config.allow_unconfirmed_access_for = 2.days 94 | 95 | # If true, requires any email changes to be confirmed (exactly the same way as 96 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 97 | # db field (see migrations). Until confirmed new email is stored in 98 | # unconfirmed email column, and copied to email column on successful confirmation. 99 | config.reconfirmable = true 100 | 101 | # Defines which key will be used when confirming an account 102 | # config.confirmation_keys = [ :email ] 103 | 104 | # ==> Configuration for :rememberable 105 | # The time the user will be remembered without asking for credentials again. 106 | # config.remember_for = 2.weeks 107 | 108 | # If true, extends the user's remember period when remembered via cookie. 109 | # config.extend_remember_period = false 110 | 111 | # Options to be passed to the created cookie. For instance, you can set 112 | # :secure => true in order to force SSL only cookies. 113 | # config.rememberable_options = {} 114 | 115 | # ==> Configuration for :validatable 116 | # Range for password length. Default is 6..128. 117 | # config.password_length = 6..128 118 | 119 | # Email regex used to validate email formats. It simply asserts that 120 | # an one (and only one) @ exists in the given string. This is mainly 121 | # to give user feedback and not to assert the e-mail validity. 122 | # config.email_regexp = /\A[^@]+@[^@]+\z/ 123 | 124 | # ==> Configuration for :timeoutable 125 | # The time you want to timeout the user session without activity. After this 126 | # time the user will be asked for credentials again. Default is 30 minutes. 127 | # config.timeout_in = 30.minutes 128 | 129 | # If true, expires auth token on session timeout. 130 | # config.expire_auth_token_on_timeout = false 131 | 132 | # ==> Configuration for :lockable 133 | # Defines which strategy will be used to lock an account. 134 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 135 | # :none = No lock strategy. You should handle locking by yourself. 136 | # config.lock_strategy = :failed_attempts 137 | 138 | # Defines which key will be used when locking and unlocking an account 139 | # config.unlock_keys = [ :email ] 140 | 141 | # Defines which strategy will be used to unlock an account. 142 | # :email = Sends an unlock link to the user email 143 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 144 | # :both = Enables both strategies 145 | # :none = No unlock strategy. You should handle unlocking by yourself. 146 | # config.unlock_strategy = :both 147 | 148 | # Number of authentication tries before locking an account if lock_strategy 149 | # is failed attempts. 150 | # config.maximum_attempts = 20 151 | 152 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 153 | # config.unlock_in = 1.hour 154 | 155 | # ==> Configuration for :recoverable 156 | # 157 | # Defines which key will be used when recovering the password for an account 158 | # config.reset_password_keys = [ :email ] 159 | 160 | # Time interval you can reset your password with a reset password key. 161 | # Don't put a too small interval or your users won't have the time to 162 | # change their passwords. 163 | config.reset_password_within = 6.hours 164 | 165 | # ==> Configuration for :encryptable 166 | # Allow you to use another encryption algorithm besides bcrypt (default). You can use 167 | # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, 168 | # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) 169 | # and :restful_authentication_sha1 (then you should set stretches to 10, and copy 170 | # REST_AUTH_SITE_KEY to pepper) 171 | # config.encryptor = :sha512 172 | 173 | # ==> Configuration for :token_authenticatable 174 | # Defines name of the authentication token params key 175 | # config.token_authentication_key = :auth_token 176 | 177 | # ==> Scopes configuration 178 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 179 | # "users/sessions/new". It's turned off by default because it's slower if you 180 | # are using only default views. 181 | # config.scoped_views = false 182 | 183 | # Configure the default scope given to Warden. By default it's the first 184 | # devise role declared in your routes (usually :user). 185 | # config.default_scope = :user 186 | 187 | # Set this configuration to false if you want /users/sign_out to sign out 188 | # only the current scope. By default, Devise signs out all scopes. 189 | # config.sign_out_all_scopes = true 190 | 191 | # ==> Navigation configuration 192 | # Lists the formats that should be treated as navigational. Formats like 193 | # :html, should redirect to the sign in page when the user does not have 194 | # access, but formats like :xml or :json, should return 401. 195 | # 196 | # If you have any extra navigational formats, like :iphone or :mobile, you 197 | # should add them to the navigational formats lists. 198 | # 199 | # The "*/*" below is required to match Internet Explorer requests. 200 | # config.navigational_formats = ["*/*", :html] 201 | 202 | # The default HTTP method used to sign out a resource. Default is :delete. 203 | config.sign_out_via = :delete 204 | 205 | # ==> OmniAuth 206 | # Add a new OmniAuth provider. Check the wiki for more information on setting 207 | # up on your models and hooks. 208 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' 209 | 210 | # ==> Warden configuration 211 | # If you want to use other strategies, that are not supported by Devise, or 212 | # change the failure app, you can configure them inside the config.warden block. 213 | # 214 | # config.warden do |manager| 215 | # manager.intercept_401 = false 216 | # manager.default_strategies(:scope => :user).unshift :some_external_strategy 217 | # end 218 | 219 | # ==> Mountable engine configurations 220 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 221 | # is mountable, there are some extra configurations to be taken into account. 222 | # The following options are available, assuming the engine is mounted as: 223 | # 224 | # mount MyEngine, at: "/my_engine" 225 | # 226 | # The router that invoked `devise_for`, in the example above, would be: 227 | # config.router_name = :my_engine 228 | # 229 | # When using omniauth, Devise cannot automatically set Omniauth path, 230 | # so you need to do it manually. For the users scope, it would be: 231 | # config.omniauth_path_prefix = "/my_engine/users/auth" 232 | config.secret_key = '9afb973e94e3489e605717812d972fb123926f6eae6a9ade57dda16bec8d5e24d7c3418fb2f447e6d344463d6be4e139d44bc9702dbe5589fd4f8dbc3e177d47' 233 | end 234 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [:password] 5 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | # Make sure the secret is at least 30 characters and all random, 6 | # no regular words or you'll be exposed to dictionary attacks. 7 | Dummy::Application.config.secret_token = 'bcdac80f5d343c6e0467e11eb0890afcc8dbc3444e4b029021da488220132fc70577ee07841db38e2d6ebec70284d60a4edde06955cc5609ffc5bed35de56b3a' 8 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' 4 | -------------------------------------------------------------------------------- /spec/dummy/config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | errors: 5 | messages: 6 | expired: "has expired, please request a new one" 7 | not_found: "not found" 8 | already_confirmed: "was already confirmed, please try signing in" 9 | not_locked: "was not locked" 10 | not_saved: 11 | one: "1 error prohibited this %{resource} from being saved:" 12 | other: "%{count} errors prohibited this %{resource} from being saved:" 13 | 14 | devise: 15 | failure: 16 | already_authenticated: 'You are already signed in.' 17 | unauthenticated: 'You need to sign in or sign up before continuing.' 18 | unconfirmed: 'You have to confirm your account before continuing.' 19 | locked: 'Your account is locked.' 20 | invalid: 'Invalid email or password.' 21 | invalid_token: 'Invalid authentication token.' 22 | timeout: 'Your session expired, please sign in again to continue.' 23 | inactive: 'Your account was not activated yet.' 24 | sessions: 25 | signed_in: 'Signed in successfully.' 26 | signed_out: 'Signed out successfully.' 27 | passwords: 28 | send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' 29 | updated: 'Your password was changed successfully. You are now signed in.' 30 | updated_not_active: 'Your password was changed successfully.' 31 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 32 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 33 | confirmations: 34 | send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.' 35 | send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes.' 36 | confirmed: 'Your account was successfully confirmed. You are now signed in.' 37 | registrations: 38 | signed_up: 'Welcome! You have signed up successfully.' 39 | signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.' 40 | signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.' 41 | signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.' 42 | updated: 'You updated your account successfully.' 43 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." 44 | destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' 45 | unlocks: 46 | send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' 47 | unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' 48 | send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.' 49 | omniauth_callbacks: 50 | success: 'Successfully authenticated from %{kind} account.' 51 | failure: 'Could not authenticate you from %{kind} because "%{reason}".' 52 | mailer: 53 | confirmation_instructions: 54 | subject: 'Confirmation instructions' 55 | reset_password_instructions: 56 | subject: 'Reset password instructions' 57 | unlock_instructions: 58 | subject: 'Unlock Instructions' 59 | -------------------------------------------------------------------------------- /spec/dummy/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | hello: "Hello world" 3 | -------------------------------------------------------------------------------- /spec/dummy/config/routes.rb: -------------------------------------------------------------------------------- 1 | Dummy::Application.routes.draw do 2 | ActiveAdmin.routes(self) 3 | 4 | devise_for :admin_users, ActiveAdmin::Devise.config 5 | 6 | root to: 'orders#show' 7 | resources :orders 8 | end 9 | -------------------------------------------------------------------------------- /spec/dummy/config/secrets.yml: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key is used for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | 6 | # Make sure the secret is at least 30 characters and all random, 7 | # no regular words or you'll be exposed to dictionary attacks. 8 | # You can use `rake secret` to generate a secure secret key. 9 | 10 | # Make sure the secrets in this file are kept private 11 | # if you're sharing your code publicly. 12 | 13 | development: 14 | secret_key_base: a62ca963571d309f1e2d63f4cc9d8e010c800b92be69003e67f5693695df7d17a221a3a34a48c6574becd9fa8d286d78aaa8b86a08bf56926f2d225cbeb13540 15 | 16 | test: 17 | secret_key_base: 81d94b29e2ecf113e9cbfbf37074403a481f874bede01b5c7429b50f020a70aa6f39458d2a15f98c1014e6b453e8737066ef3932ad1732f18ad99b1264998a61 18 | 19 | # Do not keep production secrets in the repository, 20 | # instead read values from the environment. 21 | production: 22 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> 23 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20120821181654_create_orders.rb: -------------------------------------------------------------------------------- 1 | class CreateOrders < ActiveRecord::Migration 2 | def change 3 | create_table :orders do |t| 4 | t.integer :quantity 5 | t.decimal :price 6 | t.string :customer 7 | t.date :placed 8 | t.date :shipped 9 | 10 | t.timestamps 11 | end 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20120901044842_devise_create_admin_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateAdminUsers < ActiveRecord::Migration 2 | def migrate(direction) 3 | super 4 | # Create a default user 5 | AdminUser.create!(:email => 'admin@example.com', :password => 'password', :password_confirmation => 'password') if direction == :up 6 | end 7 | 8 | def change 9 | create_table(:admin_users) do |t| 10 | ## Database authenticatable 11 | t.string :email, :null => false, :default => "" 12 | t.string :encrypted_password, :null => false, :default => "" 13 | 14 | ## Recoverable 15 | t.string :reset_password_token 16 | t.datetime :reset_password_sent_at 17 | 18 | ## Rememberable 19 | t.datetime :remember_created_at 20 | 21 | ## Trackable 22 | t.integer :sign_in_count, :default => 0 23 | t.datetime :current_sign_in_at 24 | t.datetime :last_sign_in_at 25 | t.string :current_sign_in_ip 26 | t.string :last_sign_in_ip 27 | 28 | ## Confirmable 29 | # t.string :confirmation_token 30 | # t.datetime :confirmed_at 31 | # t.datetime :confirmation_sent_at 32 | # t.string :unconfirmed_email # Only if using reconfirmable 33 | 34 | ## Lockable 35 | # t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts 36 | # t.string :unlock_token # Only if unlock strategy is :email or :both 37 | # t.datetime :locked_at 38 | 39 | ## Token authenticatable 40 | # t.string :authentication_token 41 | 42 | 43 | t.timestamps 44 | end 45 | 46 | add_index :admin_users, :email, :unique => true 47 | add_index :admin_users, :reset_password_token, :unique => true 48 | # add_index :admin_users, :confirmation_token, :unique => true 49 | # add_index :admin_users, :unlock_token, :unique => true 50 | # add_index :admin_users, :authentication_token, :unique => true 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20120901044906_create_admin_notes.rb: -------------------------------------------------------------------------------- 1 | class CreateAdminNotes < ActiveRecord::Migration 2 | def self.up 3 | create_table :admin_notes do |t| 4 | t.string :resource_id, :null => false 5 | t.string :resource_type, :null => false 6 | t.references :admin_user, :polymorphic => true 7 | t.text :body 8 | t.timestamps 9 | end 10 | add_index :admin_notes, [:resource_type, :resource_id] 11 | add_index :admin_notes, [:admin_user_type, :admin_user_id] 12 | end 13 | 14 | def self.down 15 | drop_table :admin_notes 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20120901044907_move_admin_notes_to_comments.rb: -------------------------------------------------------------------------------- 1 | class MoveAdminNotesToComments < ActiveRecord::Migration 2 | def self.up 3 | remove_index :admin_notes, [:admin_user_type, :admin_user_id] 4 | rename_table :admin_notes, :active_admin_comments 5 | rename_column :active_admin_comments, :admin_user_type, :author_type 6 | rename_column :active_admin_comments, :admin_user_id, :author_id 7 | add_column :active_admin_comments, :namespace, :string 8 | add_index :active_admin_comments, [:namespace] 9 | add_index :active_admin_comments, [:author_type, :author_id] 10 | 11 | # Update all the existing comments to the default namespace 12 | say "Updating any existing comments to the #{ActiveAdmin.application.default_namespace} namespace." 13 | execute "UPDATE active_admin_comments SET namespace='#{ActiveAdmin.application.default_namespace}'" 14 | end 15 | 16 | def self.down 17 | remove_index :active_admin_comments, :column => [:author_type, :author_id] 18 | remove_index :active_admin_comments, :column => [:namespace] 19 | remove_column :active_admin_comments, :namespace 20 | rename_column :active_admin_comments, :author_id, :admin_user_id 21 | rename_column :active_admin_comments, :author_type, :admin_user_type 22 | rename_table :active_admin_comments, :admin_notes 23 | add_index :admin_notes, [:admin_user_type, :admin_user_id] 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20121029183622_create_rules.rules.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from rules (originally 20120831163952) 2 | class CreateRules < ActiveRecord::Migration 3 | def change 4 | create_table :rules_rules do |t| 5 | t.belongs_to :rule_set 6 | t.text :expression 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/dummy/db/migrate/20121029183623_create_rule_sets.rules.rb: -------------------------------------------------------------------------------- 1 | # This migration comes from rules (originally 20120831173835) 2 | class CreateRuleSets < ActiveRecord::Migration 3 | def change 4 | create_table :rules_rule_sets do |t| 5 | t.belongs_to :source, polymorphic: true 6 | t.string :evaluation_logic 7 | 8 | t.timestamps 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /spec/dummy/db/schema.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # This file is auto-generated from the current state of the database. Instead 3 | # of editing this file, please use the migrations feature of Active Record to 4 | # incrementally modify your database, and then regenerate this schema definition. 5 | # 6 | # Note that this schema.rb definition is the authoritative source for your 7 | # database schema. If you need to create the application database on another 8 | # system, you should be using db:schema:load, not running all the migrations 9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 10 | # you'll amass, the slower it'll run and the greater likelihood for issues). 11 | # 12 | # It's strongly recommended that you check this file into your version control system. 13 | 14 | ActiveRecord::Schema.define(version: 20121029183623) do 15 | 16 | create_table "active_admin_comments", force: :cascade do |t| 17 | t.string "resource_id", null: false 18 | t.string "resource_type", null: false 19 | t.integer "author_id" 20 | t.string "author_type" 21 | t.text "body" 22 | t.datetime "created_at" 23 | t.datetime "updated_at" 24 | t.string "namespace" 25 | end 26 | 27 | add_index "active_admin_comments", ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id" 28 | add_index "active_admin_comments", ["namespace"], name: "index_active_admin_comments_on_namespace" 29 | add_index "active_admin_comments", ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id" 30 | 31 | create_table "admin_users", force: :cascade do |t| 32 | t.string "email", default: "", null: false 33 | t.string "encrypted_password", default: "", null: false 34 | t.string "reset_password_token" 35 | t.datetime "reset_password_sent_at" 36 | t.datetime "remember_created_at" 37 | t.integer "sign_in_count", default: 0 38 | t.datetime "current_sign_in_at" 39 | t.datetime "last_sign_in_at" 40 | t.string "current_sign_in_ip" 41 | t.string "last_sign_in_ip" 42 | t.datetime "created_at" 43 | t.datetime "updated_at" 44 | end 45 | 46 | add_index "admin_users", ["email"], name: "index_admin_users_on_email", unique: true 47 | add_index "admin_users", ["reset_password_token"], name: "index_admin_users_on_reset_password_token", unique: true 48 | 49 | create_table "orders", force: :cascade do |t| 50 | t.integer "quantity" 51 | t.decimal "price" 52 | t.string "customer" 53 | t.date "placed" 54 | t.date "shipped" 55 | t.datetime "created_at" 56 | t.datetime "updated_at" 57 | end 58 | 59 | create_table "rules_rule_sets", force: :cascade do |t| 60 | t.integer "source_id" 61 | t.string "source_type" 62 | t.string "evaluation_logic" 63 | t.datetime "created_at" 64 | t.datetime "updated_at" 65 | end 66 | 67 | create_table "rules_rules", force: :cascade do |t| 68 | t.integer "rule_set_id" 69 | t.text "expression" 70 | t.datetime "created_at" 71 | t.datetime "updated_at" 72 | end 73 | 74 | end 75 | -------------------------------------------------------------------------------- /spec/dummy/db/seeds.rb: -------------------------------------------------------------------------------- 1 | AdminUser.create! email: 'admin@example.com', password: 'password' 2 | -------------------------------------------------------------------------------- /spec/dummy/lib/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/lib/assets/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/log/.gitkeep -------------------------------------------------------------------------------- /spec/dummy/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The page you were looking for doesn't exist.

23 |

You may have mistyped the address or the page may have moved.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The change you wanted was rejected.

23 |

Maybe you tried to change something you didn't have access to.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/dummy/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

We're sorry, but something went wrong.

23 |
24 | 25 | 26 | -------------------------------------------------------------------------------- /spec/dummy/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azach/rules/f26b243e53cd2884a820ef82bfd93c1661de89a2/spec/dummy/public/favicon.ico -------------------------------------------------------------------------------- /spec/dummy/script/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. 3 | 4 | APP_PATH = File.expand_path('../../config/application', __FILE__) 5 | require File.expand_path('../../config/boot', __FILE__) 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /spec/rules/evaluators/definitions_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Evaluators do 4 | describe 'equals' do 5 | it 'returns true if two objects are the same' do 6 | Rules::Evaluators.list[:equals].evaluate(1.0, 1.0).should be_truthy 7 | Rules::Evaluators.list[:equals].evaluate('romeo', 'romeo').should be_truthy 8 | Rules::Evaluators.list[:equals].evaluate(['a', 'b'], ['a', 'b']).should be_truthy 9 | end 10 | 11 | it 'returns false if two objects are not the same' do 12 | Rules::Evaluators.list[:equals].evaluate(1.0, 1.3).should be_falsey 13 | Rules::Evaluators.list[:equals].evaluate('romeo', 'juliet').should be_falsey 14 | Rules::Evaluators.list[:equals].evaluate(['a', 'b'], ['a', 'c']).should be_falsey 15 | end 16 | end 17 | 18 | describe 'not_equals' do 19 | it 'returns false if two objects are the same' do 20 | Rules::Evaluators.list[:not_equals].evaluate(1.0, 1.0).should be_falsey 21 | Rules::Evaluators.list[:not_equals].evaluate('romeo', 'romeo').should be_falsey 22 | Rules::Evaluators.list[:not_equals].evaluate(['a', 'b'], ['a', 'b']).should be_falsey 23 | end 24 | 25 | it 'returns true if two objects are not the same' do 26 | Rules::Evaluators.list[:not_equals].evaluate(1.0, 1.3).should be_truthy 27 | Rules::Evaluators.list[:not_equals].evaluate('romeo', 'juliet').should be_truthy 28 | Rules::Evaluators.list[:not_equals].evaluate(['a', 'b'], ['a', 'c']).should be_truthy 29 | end 30 | end 31 | 32 | describe 'nil' do 33 | it 'returns true if an object is nil' do 34 | Rules::Evaluators.list[:nil].evaluate(nil).should be_truthy 35 | end 36 | 37 | it 'returns false if an object is not nil' do 38 | Rules::Evaluators.list[:nil].evaluate(stub('real')).should be_falsey 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /spec/rules/evaluators/evaluator_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Evaluators::Evaluator do 4 | describe '#evaluate' do 5 | let(:evaluator) { Rules::Evaluators::Evaluator.new(:test) } 6 | let(:lhv) { 'lhv' } 7 | let(:rhv) { 'rhv' } 8 | 9 | it 'raises an error if a block is not defined' do 10 | expect { 11 | evaluator.evaluate(lhv, rhv) 12 | }.to raise_error 'Unknown evaluation method' 13 | end 14 | 15 | it 'calls the block for the evaluator with the specified' do 16 | evaluator.evaluation_method = ->(lhv, rhv) { true } 17 | evaluator.evaluation_method.should_receive(:call).with(lhv, rhv) 18 | evaluator.evaluate(lhv, rhv) 19 | end 20 | 21 | context 'when an error is raised within the evaluator' do 22 | before { evaluator.evaluation_method = ->(lhv, rhv) { raise 'oh noes' } } 23 | 24 | it 'returns false by default' do 25 | evaluator.evaluate(lhv, rhv).should be_falsey 26 | end 27 | 28 | it 'raises the error if the errors_are_false config option is false' do 29 | Rules.config.stub(errors_are_false?: false) 30 | expect { 31 | evaluator.evaluate(lhv, rhv) 32 | }.to raise_error 'oh noes' 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /spec/rules/evaluators_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Evaluators do 4 | describe '.define_evaluator' do 5 | it 'fails if the key already exists' do 6 | Rules::Evaluators.define_evaluator :duplicate 7 | expect { 8 | Rules::Evaluators.define_evaluator :duplicate 9 | }.to raise_error('Evaluator already exists') 10 | end 11 | 12 | it 'creates a new evaluator object' do 13 | evaluator = Rules::Evaluators.define_evaluator :create 14 | evaluator.should be_instance_of(Rules::Evaluators::Evaluator) 15 | end 16 | 17 | it 'sets the properties of the evaluator' do 18 | evaluator = Rules::Evaluators.define_evaluator :set do 19 | self.evaluation_method = ->(lhs, rhs) { lhs == rhs } 20 | self.name = 'some name' 21 | end 22 | evaluator.evaluation_method.should_not be_nil 23 | evaluator.name.should == 'some name' 24 | end 25 | 26 | it 'adds the evaluator to a hash of evaluators' do 27 | expect { 28 | Rules::Evaluators.define_evaluator :add 29 | }.to change { Rules::Evaluators.list[:add] }.from(nil) 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/rules/parameters/attribute_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Parameters::Attribute do 4 | let (:user) do 5 | stub('user', name: 'terry').tap do |u| 6 | u.stub_chain(:account, :balance).and_return(100) 7 | end 8 | end 9 | 10 | let(:attribute) { Rules::Parameters::Attribute.new(key: 'test_key') } 11 | 12 | describe '#evaluate' do 13 | 14 | it 'retrieves the attribute value from the given hash' do 15 | attribute.evaluate(key_1: 1, key_2: 'john', test_key: 'carol').should == 'carol' 16 | end 17 | 18 | context 'when the attribute is missing' do 19 | it 'returns nil by default' do 20 | attribute.evaluate(key_1: 1, key_2: 'john').should be_nil 21 | end 22 | 23 | it 'raises an error if set in the configuration settings' do 24 | Rules.config.stub(missing_attributes_are_nil?: false) 25 | 26 | expect { 27 | attribute.evaluate(key_1: 1, key_2: 'john') 28 | }.to raise_error KeyError 29 | end 30 | end 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /spec/rules/parameters_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Parameters do 4 | 5 | end 6 | -------------------------------------------------------------------------------- /spec/rules/rule_set_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::RuleSet do 4 | let(:rule_set) { Rules::RuleSet.new } 5 | let(:attributes) { {attribute1: {name: 'name of attribute 1'}, attribute2: {name: 'name of attribute 2'}} } 6 | 7 | before { stub_const('FakeClass', Class.new) } 8 | 9 | describe '.set_attributes_for' do 10 | it 'returns an empty hash if there are no attributes for the given class' do 11 | Rules::RuleSet.attributes[FakeClass].should == {} 12 | end 13 | 14 | it 'stores the list of attributes for the specified class' do 15 | Rules::RuleSet.set_attributes_for(FakeClass, attributes) 16 | Rules::RuleSet.attributes[FakeClass].should have(2).attributes 17 | end 18 | 19 | it 'appends new attributes when called multiple times' do 20 | Rules::RuleSet.set_attributes_for(FakeClass, attributes) 21 | Rules::RuleSet.set_attributes_for(FakeClass, {attribute3: {name: 'name of attribute 3'}}) 22 | Rules::RuleSet.attributes[FakeClass].should have(3).attributes 23 | end 24 | end 25 | 26 | describe '#evaluate' do 27 | let(:true_rule1) { Rules::Rule.new(lhs_parameter_key: 'today', evaluator_key: 'not_nil') } 28 | let(:true_rule2) { Rules::Rule.new(lhs_parameter_key: nil, evaluator_key: 'nil') } 29 | let(:false_rule1) { Rules::Rule.new(lhs_parameter_key: 'today', evaluator_key: 'nil') } 30 | let(:false_rule2) { Rules::Rule.new(lhs_parameter_key: nil, evaluator_key: 'not_nil') } 31 | 32 | it 'returns true if there are no rules' do 33 | rule_set.evaluate.should be_truthy 34 | end 35 | 36 | context 'when evaluation logic is all' do 37 | before { rule_set.evaluation_logic = 'all' } 38 | 39 | it 'returns true if all rules are true' do 40 | rule_set.rules += [true_rule1, true_rule2] 41 | rule_set.evaluate.should be_truthy 42 | end 43 | 44 | it 'returns false if any rules are false' do 45 | rule_set.rules += [true_rule1, false_rule1] 46 | rule_set.evaluate.should be_falsey 47 | end 48 | end 49 | 50 | context 'when evaluation logic is any' do 51 | before { rule_set.evaluation_logic = 'any' } 52 | 53 | it 'returns true if all rules are true' do 54 | rule_set.rules += [true_rule1, true_rule2] 55 | rule_set.evaluate.should be_truthy 56 | end 57 | 58 | it 'returns true if a single rule is true' do 59 | rule_set.rules += [false_rule1, true_rule1] 60 | rule_set.evaluate.should be_truthy 61 | end 62 | 63 | it 'returns false if all rules are false' do 64 | rule_set.rules += [false_rule1, false_rule2] 65 | rule_set.evaluate.should be_falsey 66 | end 67 | end 68 | end 69 | 70 | describe '#attributes' do 71 | before { Rules::RuleSet.set_attributes_for(FakeClass, attributes) } 72 | 73 | it 'returns an empty hash if there is no source' do 74 | rule_set.attributes.should == {} 75 | end 76 | 77 | it 'returns an empty hash if the class has no defined attributes' do 78 | rule_set.stub(source: Object.new) 79 | rule_set.attributes.should == {} 80 | end 81 | 82 | it 'returns a list of attributes for its source class' do 83 | rule_set.stub(source: FakeClass.new) 84 | rule_set.attributes.should have(2).attributes 85 | end 86 | 87 | it 'returns the attribute as an attributized object' do 88 | rule_set.stub(source: FakeClass.new) 89 | rule_set.attributes[:attribute1].should be_kind_of(Rules::Parameters::Attribute) 90 | end 91 | 92 | it 'stores the key and name on the attribute object' do 93 | rule_set.stub(source: FakeClass.new) 94 | attribute = rule_set.attributes[:attribute1] 95 | 96 | attribute.key.should == :attribute1 97 | attribute.name.should == 'name of attribute 1' 98 | end 99 | end 100 | end 101 | -------------------------------------------------------------------------------- /spec/rules/rule_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Rules::Rule do 4 | let(:rule_set) { Rules::RuleSet.new } 5 | let(:evaluator_key) { 'equals' } 6 | let(:lhs) { 'today' } 7 | let(:rhs_key) { 'today' } 8 | let(:rhs_raw) { Date.today.to_s } 9 | 10 | describe 'validations' do 11 | it 'requires a valid evaluator' do 12 | rule = Rules::Rule.new(evaluator_key: 'fake') 13 | rule.should_not be_valid 14 | rule.errors[:evaluator_key].should include("is not included in the list") 15 | end 16 | 17 | it 'requires a lhs parameter' do 18 | rule = Rules::Rule.new(evaluator_key: evaluator_key) 19 | rule.should_not be_valid 20 | rule.errors[:lhs_parameter_key].should include("is not a valid parameter") 21 | end 22 | 23 | it 'requires a valid lhs parameter' do 24 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: 'fake') 25 | rule.should_not be_valid 26 | rule.errors[:lhs_parameter_key].should include("is not a valid parameter") 27 | end 28 | 29 | it 'requires a rhs parameter if the evaluator requires one' do 30 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: lhs) 31 | rule.should_not be_valid 32 | rule.errors[:rhs_parameter_key].should include("can't be blank") 33 | end 34 | 35 | it 'requires a blank rhs parameter if the evaluator does not require one' do 36 | rule = Rules::Rule.new(evaluator_key: 'nil', lhs_parameter_key: lhs, rhs_parameter_raw: rhs_raw) 37 | rule.should_not be_valid 38 | rule.errors[:rhs_parameter_raw].should include("must be blank") 39 | end 40 | 41 | it 'requires a valid rhs parameter key if provided' do 42 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: lhs, rhs_parameter_key: 'fake') 43 | rule.should_not be_valid 44 | rule.errors[:rhs_parameter_key].should include("is not a valid parameter") 45 | end 46 | 47 | it 'requires that only one of the rhs parameter key or raw value are set' do 48 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: lhs, rhs_parameter_key: rhs_key, rhs_parameter_raw: rhs_raw) 49 | rule.should_not be_valid 50 | rule.errors[:rhs_parameter_key].should include("must be blank") 51 | end 52 | 53 | it 'allows a lhs parameter with a valid constant key' do 54 | rule = Rules::Rule.new(evaluator_key: 'nil', lhs_parameter_key: 'today') 55 | rule.should be_valid 56 | end 57 | 58 | it 'allows a lhs parameter with a valid attribute key' do 59 | rule_set.stub(attributes: {current_user: 'The current user'}) 60 | rule = Rules::Rule.new(rule_set: rule_set, evaluator_key: 'nil', lhs_parameter_key: 'current_user') 61 | rule.should be_valid 62 | end 63 | 64 | it 'is valid for well defined rules' do 65 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: lhs, rhs_parameter_raw: rhs_raw) 66 | rule.should be_valid 67 | 68 | rule = Rules::Rule.new(evaluator_key: evaluator_key, lhs_parameter_key: lhs, rhs_parameter_key: rhs_key) 69 | rule.should be_valid 70 | 71 | rule = Rules::Rule.new(evaluator_key: 'nil', lhs_parameter_key: lhs) 72 | rule.should be_valid 73 | end 74 | end 75 | 76 | describe '#evaluator' do 77 | it 'returns nil if an evaluator does not exist for a key' do 78 | rule = Rules::Rule.new(evaluator_key: 'fake') 79 | rule.evaluator.should be_nil 80 | end 81 | 82 | it 'returns the evaluator if an evaluator with the key exists' do 83 | rule = Rules::Rule.new(evaluator_key: evaluator_key) 84 | rule.evaluator.should be_kind_of(Rules::Evaluators::Evaluator) 85 | end 86 | end 87 | 88 | describe '#lhs_parameter_value' do 89 | it 'returns nil if the parameter key does not have a corresponding attribute' do 90 | rule = Rules::Rule.new(lhs_parameter_key: 'fake') 91 | rule.lhs_parameter_value.should be_nil 92 | end 93 | 94 | it 'returns the evaluated attribute for a constant key' do 95 | rule = Rules::Rule.new(lhs_parameter_key: 'today') 96 | rule.lhs_parameter_value.should == Time.now.utc.to_date 97 | end 98 | 99 | it 'returns the right value for an attribute' do 100 | current_user = double('current user') 101 | current_user_attribute = Rules::Parameters::Attribute.new(key: :current_user, name: 'the current user') 102 | rule_set.stub(attributes: {current_user: current_user_attribute}) 103 | 104 | rule = Rules::Rule.new(rule_set: rule_set, lhs_parameter_key: 'current_user') 105 | 106 | rule.lhs_parameter_value({ 107 | current_user: current_user, 108 | current_price: 10 109 | }).should == current_user 110 | end 111 | end 112 | 113 | describe '#rhs_parameter_value' do 114 | context 'with a raw value' do 115 | it 'returns the original value of the lhs parameter does not require a cast' do 116 | rule = Rules::Rule.new(rhs_parameter_raw: 'some string') 117 | rule.rhs_parameter_value.should == 'some string' 118 | end 119 | 120 | it 'raises an error for rhs parameters that can not be cast' do 121 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: 'four score and seven years ago') 122 | expect { 123 | rule.rhs_parameter_value 124 | }.to raise_error 125 | end 126 | 127 | it 'casts the rhs parameter into the format required by the lhs parameter' do 128 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: '2012-01-01') 129 | rule.rhs_parameter_value.should == Date.parse('2012-01-01') 130 | end 131 | 132 | it 'casts the rhs parameter into the format required by the evaluator' do 133 | rule = Rules::Rule.new(evaluator_key: 'matches', rhs_parameter_raw: 'test$') 134 | rule.rhs_parameter_value.should == Regexp.new('test$') 135 | end 136 | end 137 | 138 | context 'with a parameter key' do 139 | it 'returns nil if the parameter key does not have a corresponding attribute' do 140 | rule = Rules::Rule.new(rhs_parameter_key: 'fake') 141 | rule.rhs_parameter_value.should be_nil 142 | end 143 | 144 | it 'returns the evaluated attribute for a constant key' do 145 | rule = Rules::Rule.new(rhs_parameter_key: 'today') 146 | rule.rhs_parameter_value.should == Time.now.utc.to_date 147 | end 148 | 149 | it 'returns the right value for an attribute' do 150 | current_user = double('current user') 151 | current_user_attribute = Rules::Parameters::Attribute.new(key: :current_user, name: 'the current user') 152 | rule_set.stub(attributes: {current_user: current_user_attribute}) 153 | 154 | rule = Rules::Rule.new(rule_set: rule_set, rhs_parameter_key: 'current_user') 155 | 156 | rule.rhs_parameter_value({ 157 | current_user: current_user, 158 | current_price: 10 159 | }).should == current_user 160 | end 161 | end 162 | end 163 | 164 | describe '#lhs_parameter' do 165 | it 'returns nil if the parameter key does not have a corresponding attribute' do 166 | rule = Rules::Rule.new(lhs_parameter_key: 'fake') 167 | rule.lhs_parameter.should be_nil 168 | end 169 | 170 | it 'returns the constant for the parameter key if defined' do 171 | rule = Rules::Rule.new(lhs_parameter_key: lhs) 172 | rule.lhs_parameter.should be_kind_of(Rules::Parameters::Constant) 173 | end 174 | 175 | it 'returns the attribute for the parameter key if defined' do 176 | rule_set.stub(attributes: {current_user: Rules::Parameters::Attribute.new(key: :current_user)}) 177 | rule = Rules::Rule.new(rule_set: rule_set, lhs_parameter_key: 'current_user') 178 | rule.lhs_parameter.should be_kind_of(Rules::Parameters::Attribute) 179 | end 180 | end 181 | 182 | describe '#rhs_parameter' do 183 | context 'with a raw value' do 184 | it 'returns the raw value' do 185 | rule = Rules::Rule.new(rhs_parameter_raw: 'value') 186 | rule.rhs_parameter.should == 'value' 187 | end 188 | end 189 | 190 | context 'with a parameter key' do 191 | it 'returns nil if the parameter key does not have a corresponding attribute' do 192 | rule = Rules::Rule.new(rhs_parameter_key: 'fake') 193 | rule.rhs_parameter.should be_nil 194 | end 195 | 196 | it 'returns the constant for the parameter key if defined' do 197 | rule = Rules::Rule.new(rhs_parameter_key: rhs_key) 198 | rule.rhs_parameter.should be_kind_of(Rules::Parameters::Constant) 199 | end 200 | 201 | it 'returns the attribute for the parameter key if defined' do 202 | rule_set.stub(attributes: {current_user: Rules::Parameters::Attribute.new(key: :current_user)}) 203 | rule = Rules::Rule.new(rule_set: rule_set, rhs_parameter_key: 'current_user') 204 | rule.rhs_parameter.should be_kind_of(Rules::Parameters::Attribute) 205 | end 206 | end 207 | end 208 | 209 | describe '#evaluate' do 210 | let(:email_attribute) { Rules::Parameters::Attribute.new(key: :email_address) } 211 | let(:name_attribute) { Rules::Parameters::Attribute.new(key: :name) } 212 | 213 | before { rule_set.stub(attributes: {email_address: email_attribute, name: name_attribute}) } 214 | 215 | it 'returns true for rules that meet the conditions' do 216 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: Time.now.utc.to_date, evaluator_key: 'equals') 217 | rule.evaluate.should be_truthy 218 | 219 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: 2.weeks.ago.to_s, evaluator_key: 'not_equals') 220 | rule.evaluate.should be_truthy 221 | 222 | rule = Rules::Rule.new(lhs_parameter_key: :email_address, rhs_parameter_raw: /example.com$/, evaluator_key: 'matches', rule_set: rule_set) 223 | rule.evaluate(email_address: 'test@example.com').should be_truthy 224 | 225 | rule = Rules::Rule.new(lhs_parameter_key: :email_address, rhs_parameter_key: :name, evaluator_key: 'contains', rule_set: rule_set) 226 | rule.evaluate(email_address: 'sally@example.com', name: 'sally').should be_truthy 227 | end 228 | 229 | it 'returns false for rules that do not meet the conditions' do 230 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: Time.now.utc.to_date, evaluator_key: 'not_equals') 231 | rule.evaluate.should be_falsey 232 | 233 | rule = Rules::Rule.new(lhs_parameter_key: 'today', rhs_parameter_raw: 2.weeks.ago.to_s, evaluator_key: 'equals') 234 | rule.evaluate.should be_falsey 235 | 236 | rule = Rules::Rule.new(lhs_parameter_key: :email_address, rhs_parameter_raw: /example.com$/, evaluator_key: 'not_matches', rule_set: rule_set) 237 | rule.evaluate(email_address: 'test@example.com').should be_falsey 238 | 239 | rule = Rules::Rule.new(lhs_parameter_key: :email_address, rhs_parameter_key: :name, evaluator_key: 'contains', rule_set: rule_set) 240 | rule.evaluate(email_address: 'sally@example.com', name: 'terry').should be_falsey 241 | end 242 | end 243 | 244 | describe '#valid_attributes' do 245 | it 'returns an empty array with no rule set' do 246 | rule = Rules::Rule.new 247 | rule.valid_attributes.should be_empty 248 | end 249 | 250 | it 'returns an empty array with a rule set with no attributes' do 251 | rule = Rules::Rule.new(rule_set: rule_set) 252 | rule.valid_attributes.should be_empty 253 | end 254 | 255 | it 'returns the right attribute list when the associated rule set is unsaved' do 256 | rule = Order.new.rule_set.rules.build 257 | rule.valid_attributes.should_not be_empty 258 | end 259 | 260 | it 'returns a list of attributes for a rule set' do 261 | rule_set.stub(attributes: {current_user: double('attribute'), order_price: double('attribute')}) 262 | rule = Rules::Rule.new(rule_set: rule_set) 263 | rule.should have(2).valid_attributes 264 | end 265 | end 266 | end 267 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # This file is copied to spec/ when you run 'rails generate rspec:install' 2 | ENV["RAILS_ENV"] ||= 'test' 3 | require File.expand_path("../dummy/config/environment", __FILE__) 4 | require 'rspec/rails' 5 | require 'rspec/autorun' 6 | require 'rspec/collection_matchers' 7 | 8 | # Requires supporting ruby files with custom matchers and macros, etc, 9 | # in spec/support/ and its subdirectories. 10 | Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 11 | 12 | RSpec.configure do |config| 13 | # ## Mock Framework 14 | # 15 | # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: 16 | # 17 | # config.mock_with :mocha 18 | # config.mock_with :flexmock 19 | # config.mock_with :rr 20 | 21 | # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 22 | config.fixture_path = "#{::Rails.root}/spec/fixtures" 23 | 24 | # If you're not using ActiveRecord, or you'd prefer not to run each of your 25 | # examples within a transaction, remove the following line or assign false 26 | # instead of true. 27 | config.use_transactional_fixtures = true 28 | 29 | # If true, the base class of anonymous controllers will be inferred 30 | # automatically. This will be the default behavior in future versions of 31 | # rspec-rails. 32 | config.infer_base_class_for_anonymous_controllers = false 33 | 34 | # Run specs in random order to surface order dependencies. If you find an 35 | # order dependency and want to debug it, you can fix the order by providing 36 | # the seed, which is printed after each run. 37 | # --seed 1234 38 | config.order = "random" 39 | end 40 | --------------------------------------------------------------------------------