stateful_controller 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f889a5a37194f712695ca0f064fe3db76e98eee0
4
+ data.tar.gz: 10c06ed4d4820194456212d79c99049efff5e96d
5
+ SHA512:
6
+ metadata.gz: d1a710a2d2abe2633ad30799ab5964cdfc66ffd24ddb82e8c648d65f6b5a3dda49e0bedc5546611bedd5d420c99d31ecee40fca067d2dc9817281883f61ed0e5
7
+ data.tar.gz: 3645e3ea5d77dd54d9d376fd350ff8b25a23888dfc90e10e6b4eaa5eff9476701c0236cb02dbcee364b5e6a63348f02cfedcba806ddec8d112a9ff72281d4232
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # ignore local rvm config
12
+ .ruby-*
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.7
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,52 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # for local testing only!
4
+
5
+ gem 'rails', '3.2.22'
6
+
7
+ # Bundle edge Rails instead:
8
+ # gem 'rails', :git => 'git://github.com/rails/rails.git'
9
+
10
+ gem 'sqlite3'
11
+
12
+
13
+ # Gems used only for assets and not required
14
+ # in production environments by default.
15
+ group :assets do
16
+ gem 'sass-rails', '~> 3.2.3'
17
+ gem 'coffee-rails', '~> 3.2.1'
18
+
19
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
20
+ # gem 'therubyracer', :platforms => :ruby
21
+
22
+ gem 'uglifier', '>= 1.0.3'
23
+ end
24
+
25
+ gem 'jquery-rails'
26
+
27
+ # To use ActiveModel has_secure_password
28
+ # gem 'bcrypt-ruby', '~> 3.0.0'
29
+
30
+ # To use Jbuilder templates for JSON
31
+ # gem 'jbuilder'
32
+
33
+ # Use unicorn as the app server
34
+ # gem 'unicorn'
35
+
36
+ # Deploy with Capistrano
37
+ # gem 'capistrano'
38
+
39
+ # To use debugger
40
+ # gem 'debugger'
41
+
42
+ # end local
43
+
44
+ # Specify your gem's dependencies in stateful_controller.gemspec
45
+ gemspec
46
+
47
+
48
+ # keep personal choice development dependencies here (others should be in the gemspec)
49
+ group :development, :test do
50
+ gem 'pry'
51
+ gem 'pry-stack_explorer'
52
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Larry Kyrala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # StatefulController
2
+
3
+ StatefulController combines the idea of a Rails controller with a [state machine](https://en.wikipedia.org/wiki/Finite-state_machine)
4
+ that controls navigation through a sequence of views and actions (i.e. a user 'flow').
5
+
6
+ StatefulController uses the [aasm gem](https://github.com/aasm/aasm) to implement the state machine part of things, so we use its
7
+ terminology to define the state machine. A state machine can be thought of as a graph of states (vertices) connected by event transitions (edges).
8
+ A StatefulController treats states as Rails' views and events as Rails' actions. A StatefulController is a Rails controller, so you can call actions directly. But, more interestingly, you can call two special actions: *start* and *next*.
9
+
10
+ ## Example
11
+
12
+ Start with a simple controller in your Rails app:
13
+
14
+ ```ruby
15
+ class ExampleController < ApplicationController
16
+ include StatefulController
17
+
18
+ class ExampleState < StatefulController::State
19
+ end
20
+
21
+ # states are 'views' and events are 'actions'
22
+ aasm do
23
+ state :sleeping, initial: true
24
+ state :running
25
+ state :cleaning
26
+
27
+ event :run do
28
+ transitions from: :sleeping, to: :running
29
+ end
30
+
31
+ event :clean do
32
+ transitions from: :running, to: :cleaning
33
+ end
34
+
35
+ event :sleep do
36
+ transitions from: [:running, :cleaning], to: :sleeping
37
+ end
38
+ end
39
+
40
+ # controller actions here: (same names as events)
41
+ # do anything here that you need to do for your views, i.e. modify state
42
+ # load auxillary objects, etc, just like regular Rails controller actions,
43
+ # the corresponding view (state) will be automatically rendered for you.
44
+
45
+ def run
46
+ end
47
+
48
+ def clean
49
+ end
50
+
51
+ def sleep
52
+ end
53
+
54
+ private
55
+
56
+ def load_state
57
+ session[:state] || ExampleState.new
58
+ end
59
+
60
+ def save_state(s)
61
+ session[:state] = s
62
+ end
63
+
64
+ end
65
+ ```
66
+
67
+ Add some views:
68
+ (note that views are not named the same as your actions, but should match your event names!)
69
+
70
+ ```
71
+ app/
72
+ views/
73
+ example/
74
+ cleaning.html.erb
75
+ running.html.erb
76
+ sleeping.html.erb
77
+ ```
78
+
79
+
80
+ Add some routes:
81
+
82
+ ```ruby
83
+
84
+ # don't forget to add the two special routes!
85
+ get "example/start"
86
+ get "example/next"
87
+
88
+ # and your defined routes:
89
+ get "example/run"
90
+ get "example/clean"
91
+ get "example/sleep"
92
+ ```
93
+
94
+
95
+ ### What does that get us?
96
+
97
+ Try the following:
98
+
99
+ ```
100
+ http://localhost:3000/example/start # resets ExampleState, sets current_state to the aasm intial (:sleeping) and shows sleeping.html.erb
101
+ http://localhost:3000/example/next # checks the permitted events from :sleeping, fires it (:run) and shows running.html.erb
102
+ http://localhost:3000/example/next # checks the permitted events from :running, fires it (:clean) and shows cleaning.html.erb
103
+ http://localhost:3000/example/next # checks the permitted events from :cleaning, fires it (:sleep) and shows sleeping.html.erb
104
+
105
+ ```
106
+
107
+ So, the special *next* action dispatches whatever the next permitted action is (according to the state machine definition above).
108
+
109
+ What if we don't follow the rules?
110
+
111
+ ```
112
+ http://localhost:3000/example/start # resets ExampleState, sets current_state to the aasm intial (:sleeping) and shows sleeping.html.erb
113
+ http://localhost:3000/example/clean # tries to send event :clean, but raises:
114
+ AASM::InvalidTransition in ExampleController#clean
115
+ Event 'clean' cannot transition from 'sleeping'
116
+ ```
117
+
118
+ ### Summary
119
+
120
+ You can define the legal transitions in your user flow in the state machine and StatefulController will enforce that flow for you, which
121
+ greatly simplifies the Rails controller logic for complex flows. See the source for the dummy Rails application which has more detail and
122
+ interactive examples.
123
+
124
+
125
+
126
+ ## Installation
127
+
128
+ Add this line to your application's Gemfile:
129
+
130
+ ```ruby
131
+ gem 'stateful_controller'
132
+ ```
133
+
134
+ And then execute:
135
+
136
+ $ bundle
137
+
138
+ Or install it yourself as:
139
+
140
+ $ gem install stateful_controller
141
+
142
+ ## Development
143
+
144
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
145
+
146
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
147
+
148
+ ## Contributing
149
+
150
+ Bug reports and pull requests are welcome on GitHub at https://github.com/coldnebo/stateful_controller. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
151
+
152
+
153
+ ## License
154
+
155
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
156
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "stateful_controller"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,3 @@
1
+ module StatefulController
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,125 @@
1
+ require 'stateful_controller/version'
2
+ require 'active_support/concern'
3
+ require 'aasm'
4
+ require 'ostruct'
5
+
6
+ module StatefulController
7
+ extend ActiveSupport::Concern
8
+
9
+ class State
10
+ attr_accessor :current_state
11
+ end
12
+
13
+ included do
14
+ include AASM
15
+ attr_reader :state
16
+ helper_method :state
17
+ before_filter :__load_and_process, except: :start
18
+ after_filter :__finish
19
+
20
+ # this section removes the event methods that aasm normally adds to the including object.
21
+ # # because this object is meant to be a controller, the events (actions) should obey Rails
22
+ # # behavior, so we remove the methods and manage the state transitions internally.
23
+ class << self
24
+ alias_method :aasm_orig, :aasm
25
+
26
+ def aasm(*args, &block)
27
+ ret = aasm_orig(*args, &block) # first process the state machine DSL normally
28
+ if block
29
+ # then this is a DSL call, so remove the event methods it normally makes on the the object.
30
+ methods_to_remove = aasm.events.map(&:name)
31
+ methods_to_remove.each {|method|
32
+ remove_method(method)
33
+ }
34
+ end
35
+ ret
36
+ end
37
+ end
38
+ end
39
+
40
+ # StatefulController always defines a special action called 'next' that goes to the next available transition.
41
+ def next
42
+ # this may rely on events having exactly one transition... otherwise, we may need an argument? (TBD)
43
+ next_events = aasm.events(permitted: true).map(&:name)
44
+ __debug("choosing first from next events: #{next_events.inspect}")
45
+ next_event = next_events.first
46
+ __process(next_event)
47
+ self.send(next_event)
48
+ end
49
+
50
+ # SC also has a special action called "start" which clears state and reloads it (defaulting back to the initial state)
51
+ def start
52
+ save_state(nil)
53
+ __load
54
+ end
55
+
56
+ protected
57
+
58
+ def initialize
59
+ super
60
+ end
61
+
62
+ def default_render(*args)
63
+ render aasm.current_state
64
+ end
65
+
66
+ # before filter for setup
67
+ def __load_and_process
68
+ __load
69
+
70
+ # rails action should always be something convertible to a symbol
71
+ event = params[:action].to_sym
72
+
73
+ # next is a special action, don't try to send the event.
74
+ return if event == :next
75
+
76
+ __process(event)
77
+ end
78
+
79
+ def __load
80
+ @state = load_state
81
+ __debug("load_state returned #{@state.inspect}")
82
+ raise ArgumentError, "load_state() must return a StatefulController::State or subclass." unless @state.kind_of?(State)
83
+
84
+ # allow the StatefulController to retain it's current state across requests (since controller instances are created per request in Rails)
85
+ if state.current_state.nil?
86
+ state.current_state = aasm.current_state # if load_state didn't recover a current_state, then use the aasm initial.
87
+ else
88
+ aasm.current_state = state.current_state # otherwise, set the aasm.current_state to the loaded current_state.
89
+ end
90
+ end
91
+
92
+ def __process(event)
93
+ # manually trigger the event (while we consider the aasm events as "actions", we reserve the methods in the
94
+ # controller as actual actions instead of aasm event triggering sugar.)
95
+ # adapted from ./lib/aasm/base.rb:85
96
+
97
+ # while the aasm gem supports multiple state machines per class, StatefulController always uses only one state machine, the default.
98
+ # so we may substitute :default for @name in the DSL impl:
99
+ # original line: aasm(:#{@name}).current_event = :#{name}
100
+ aasm.current_event = event
101
+
102
+ # also, aasm supports arguments for events, but because StatefulController models Rails controller actions, no arguments or blocks are supported.
103
+ # original line: aasm_fire_event(:#{@name}, :#{name}, {:persist => false}, *args, &block)
104
+ aasm_fire_event(:default, event, {persist: false}, [])
105
+ end
106
+
107
+ def __finish
108
+ state.current_state = aasm.current_state
109
+ __debug("calling save_state with #{state.inspect}")
110
+ save_state(state)
111
+ end
112
+
113
+ def load_state
114
+ raise NotImplementedError, "Controllers that include StatefulController should define the load_state() method."
115
+ end
116
+
117
+ def save_state
118
+ raise NotImplementedError, "Controllers that include StatefulController should define the save_state() method."
119
+ end
120
+
121
+ def __debug(msg)
122
+ Rails.logger.debug("DEBUG [StatefulController]: #{msg}")
123
+ end
124
+
125
+ end
@@ -0,0 +1,38 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'stateful_controller/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "stateful_controller"
8
+ spec.version = StatefulController::VERSION
9
+ spec.authors = ["Larry Kyrala"]
10
+ spec.email = ["larry.kyrala@gmail.com"]
11
+
12
+ spec.summary = %q{A StatefulController for Rails that uses a state machine to manage transitions between views.}
13
+ #spec.description = %q{TODO: Write a longer description or delete this line.}
14
+ spec.homepage = "https://github.com/coldnebo/stateful_controller"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_dependency "rails"
31
+ spec.add_dependency "aasm"
32
+
33
+ spec.add_development_dependency "bundler", "~> 1.10"
34
+ spec.add_development_dependency "rake", "~> 10.0"
35
+ spec.add_development_dependency "minitest"
36
+
37
+ spec.add_development_dependency "yard"
38
+ end
metadata ADDED
@@ -0,0 +1,143 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: stateful_controller
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Larry Kyrala
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2015-12-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: aasm
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.10'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.10'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: yard
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description:
98
+ email:
99
+ - larry.kyrala@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".travis.yml"
106
+ - CODE_OF_CONDUCT.md
107
+ - Gemfile
108
+ - LICENSE.txt
109
+ - README.md
110
+ - Rakefile
111
+ - bin/console
112
+ - bin/setup
113
+ - lib/stateful_controller.rb
114
+ - lib/stateful_controller/version.rb
115
+ - stateful_controller.gemspec
116
+ homepage: https://github.com/coldnebo/stateful_controller
117
+ licenses:
118
+ - MIT
119
+ metadata:
120
+ allowed_push_host: https://rubygems.org
121
+ post_install_message:
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubyforge_project:
137
+ rubygems_version: 2.4.8
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: A StatefulController for Rails that uses a state machine to manage transitions
141
+ between views.
142
+ test_files: []
143
+ has_rdoc: