transition_buttons 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 56cd7f848d886a443f88cb3d05e1a964c4bcc7e97e8acdd41736887f3f95bc3a
4
+ data.tar.gz: 1cf834be4961dab9dcaefa081dee0667dc10e7d2c9319aa55873df638de54a7a
5
+ SHA512:
6
+ metadata.gz: e8ce855b727b18eec80d41baed23a2a1617cb1417e0bcf0ae4cbf4a1819f6d1b182643819395aac82019286918c0754b2dbceb60ed5102e0333945ef16f561fe
7
+ data.tar.gz: ab0afecb056a98a2c03fd197a7527368ca9335e8375864ad668fb0db85623dbccd967adb35fb24131a8bff9726e035c5c7c0a4dc7ead6078499397177e196eab
data/CHANGELOG.md ADDED
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## [0.0.1] - 2026-07-08
6
+
7
+ - Reserve the gem name. Placeholder release; the first usable version will be
8
+ 0.1.0. Source extracted from the `ruby-state-machine-tests` research repo.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 First Draft
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,125 @@
1
+ # transition_buttons
2
+
3
+ Render one button per state-machine event **the current user may perform on a
4
+ record right now** — the intersection of *legal from the current state* (the
5
+ state machine's guards) and *authorized for this user* (your policy) — each
6
+ button POSTing to a member `transition` route that **re-checks both
7
+ server-side** before firing.
8
+
9
+ The buttons are a convenience for the view. The endpoint is the security
10
+ boundary: it never trusts the submitted event, re-deriving the legal-and-authorized
11
+ set independently.
12
+
13
+ Ships with adapters for [`state_machines`](https://github.com/state-machines/state_machines)
14
+ and [ActionPolicy](https://github.com/palkan/action_policy); both are swappable.
15
+
16
+ ## Install
17
+
18
+ ```ruby
19
+ # Gemfile
20
+ gem "transition_buttons"
21
+ gem "state_machines-activerecord"
22
+ gem "action_policy"
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ### 1. A model with one or more state machines
28
+
29
+ ```ruby
30
+ class Post < ApplicationRecord
31
+ state_machine :state, initial: :draft do
32
+ event(:submit) { transition draft: :pending_review }
33
+ event(:publish) { transition pending_review: :published }
34
+ event(:reject) { transition pending_review: :draft }
35
+ end
36
+
37
+ # A second machine on the same record is fully supported.
38
+ state_machine :moderation_state, initial: :ok do
39
+ event(:flag) { transition ok: :flagged }
40
+ event(:unflag) { transition flagged: :ok }
41
+ end
42
+ end
43
+ ```
44
+
45
+ ### 2. A policy whose rule names match the event names
46
+
47
+ ```ruby
48
+ class PostPolicy < ApplicationPolicy
49
+ def submit? = owner?
50
+ def publish? = editor?
51
+ def reject? = editor?
52
+ def flag? = editor?
53
+ def unflag? = editor?
54
+ end
55
+ ```
56
+
57
+ An event with no matching rule is **denied by default** — adding an event can
58
+ never silently expose it.
59
+
60
+ ### 3. Route + controller
61
+
62
+ ```ruby
63
+ # config/routes.rb
64
+ resources :posts, only: [:index, :show] do
65
+ transitionable # POST /posts/:id/transition (transition_post)
66
+ end
67
+ ```
68
+
69
+ ```ruby
70
+ class PostsController < ApplicationController
71
+ include TransitionButtons::Transitionable
72
+ # `transition` is provided. The record defaults to Post.find(params[:id]);
73
+ # override #transition_buttons_record for custom scoping.
74
+ end
75
+ ```
76
+
77
+ ### 4. The view
78
+
79
+ ```erb
80
+ <%= transition_buttons_for(@post) %> <%# machine: :state %>
81
+ <%= transition_buttons_for(@post, machine: :moderation_state) %>
82
+ <%= transition_buttons_for(@post, user: some_user, class: "btn") %>
83
+
84
+ <%# Or render your own UI from the raw permitted list: %>
85
+ <% available_events(@post).each do |event| %> ... <% end %>
86
+ ```
87
+
88
+ `user:` defaults to `current_user` when the view exposes it. Extra keyword
89
+ options are forwarded to each `button_to`.
90
+
91
+ ## Recording who triggered a transition
92
+
93
+ If your model exposes `current_actor=`, the controller sets it to `current_user`
94
+ before firing, so a transition log (e.g.
95
+ [state_machines-audit_trail](https://github.com/state-machines/state_machines-audit_trail))
96
+ can record the actor:
97
+
98
+ ```ruby
99
+ class Post < ApplicationRecord
100
+ attr_accessor :current_actor
101
+ state_machine :state, initial: :draft do
102
+ audit_trail context: :audited_by
103
+ # ...
104
+ end
105
+ def audited_by = current_actor&.email
106
+ end
107
+ ```
108
+
109
+ ## Swapping backends
110
+
111
+ ```ruby
112
+ TransitionButtons.configure do |c|
113
+ c.state_machine_adapter = MyAdapter.new # #available_events/#current_state/#fire/#event_label
114
+ c.authorizer = MyAuthorizer.new # #permitted?(user:, record:, event:, machine:)
115
+ c.default_machine = :state
116
+ end
117
+ ```
118
+
119
+ An AASM adapter (`record.aasm(machine).events(permitted: true)` /
120
+ `record.public_send("#{event}!")`) and a Pundit authorizer are natural
121
+ additions and the seams are designed for them.
122
+
123
+ ## Out of scope (v1)
124
+
125
+ Events that need arguments — those want a real form, not a one-click button.
@@ -0,0 +1,19 @@
1
+ module TransitionButtons
2
+ module Authorizers
3
+ # Authorizer backed by ActionPolicy.
4
+ #
5
+ # Convention: a transition event maps to the policy rule of the same name
6
+ # with a `?` suffix (event `:publish` -> rule `publish?`). When the policy
7
+ # defines no such rule we deny by default, so adding an event without a
8
+ # matching rule can never silently expose it.
9
+ class ActionPolicy
10
+ def permitted?(user:, record:, event:, machine:)
11
+ policy = ::ActionPolicy.lookup(record).new(record, user: user)
12
+ rule = :"#{event}?"
13
+ return false unless policy.respond_to?(rule)
14
+
15
+ policy.apply(rule)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,21 @@
1
+ require "transition_buttons/state_machine_adapters/state_machines"
2
+ require "transition_buttons/authorizers/action_policy"
3
+
4
+ module TransitionButtons
5
+ class Configuration
6
+ # Object responding to #available_events, #current_state, #fire, #event_label.
7
+ attr_accessor :state_machine_adapter
8
+
9
+ # Object responding to #permitted?(user:, record:, event:, machine:).
10
+ attr_accessor :authorizer
11
+
12
+ # Machine to target when a helper/endpoint does not specify one.
13
+ attr_accessor :default_machine
14
+
15
+ def initialize
16
+ @state_machine_adapter = StateMachineAdapters::StateMachines.new
17
+ @authorizer = Authorizers::ActionPolicy.new
18
+ @default_machine = :state
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,75 @@
1
+ module TransitionButtons
2
+ # Mixed into a host controller to add a `transition` action:
3
+ #
4
+ # class PostsController < ApplicationController
5
+ # include TransitionButtons::Transitionable
6
+ # end
7
+ #
8
+ # Paired with the `transitionable` route helper:
9
+ #
10
+ # resources :posts do
11
+ # transitionable
12
+ # end
13
+ #
14
+ # This action is the real security boundary. The view's buttons are only a
15
+ # hint; here we independently re-resolve which events are legal-and-authorized
16
+ # for the current user before firing, and refuse anything else.
17
+ module Transitionable
18
+ extend ActiveSupport::Concern
19
+
20
+ def transition
21
+ record = transition_buttons_record
22
+ machine = (params[:machine].presence || TransitionButtons.config.default_machine).to_sym
23
+ event = params.require(:event).to_sym
24
+
25
+ # Record who triggered the transition for the audit trail, if supported.
26
+ record.current_actor = current_user if record.respond_to?(:current_actor=)
27
+
28
+ resolver = EventResolver.new(record: record, user: current_user, machine: machine)
29
+
30
+ if !resolver.domain_event?(event)
31
+ transition_buttons_render_unavailable(record, event, machine)
32
+ elsif !resolver.permitted?(event)
33
+ transition_buttons_render_forbidden(record, event, machine)
34
+ elsif resolver.fire(event)
35
+ transition_buttons_render_success(record, event, machine)
36
+ else
37
+ # Legal and authorized, but the machine still refused (e.g. a guard that
38
+ # flipped between resolution and firing). Surface it rather than hide it.
39
+ transition_buttons_render_unavailable(record, event, machine)
40
+ end
41
+ end
42
+
43
+ private
44
+
45
+ # --- Overridable hooks --------------------------------------------------
46
+
47
+ # Defaults to inferring the model from the controller name and finding by
48
+ # :id (PostsController -> Post.find(params[:id])). Override for anything
49
+ # non-conventional (scoping to current_user, nested resources, etc.).
50
+ def transition_buttons_record
51
+ controller_name.classify.constantize.find(params[:id])
52
+ end
53
+
54
+ def transition_buttons_render_success(record, event, _machine)
55
+ respond_to do |format|
56
+ format.html { redirect_back fallback_location: url_for(record), notice: "#{event.to_s.humanize} succeeded." }
57
+ format.json { render json: record }
58
+ end
59
+ end
60
+
61
+ def transition_buttons_render_forbidden(record, event, _machine)
62
+ respond_to do |format|
63
+ format.html { redirect_back fallback_location: url_for(record), alert: "You are not allowed to #{event}." }
64
+ format.json { head :forbidden }
65
+ end
66
+ end
67
+
68
+ def transition_buttons_render_unavailable(record, event, _machine)
69
+ respond_to do |format|
70
+ format.html { redirect_back fallback_location: url_for(record), alert: "#{event.to_s.humanize} is not available right now." }
71
+ format.json { head :unprocessable_entity }
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,54 @@
1
+ module TransitionButtons
2
+ # Single source of truth shared by the view helper and the controller, so the
3
+ # buttons a user sees and the transitions the endpoint accepts can never drift
4
+ # apart. The view renders `permitted_events`; the controller re-derives the
5
+ # same set server-side before firing (the buttons are a hint, never the
6
+ # security boundary).
7
+ class EventResolver
8
+ attr_reader :machine
9
+
10
+ def initialize(record:, user:, machine: nil, adapter: nil, authorizer: nil)
11
+ @record = record
12
+ @user = user
13
+ @machine = (machine || TransitionButtons.config.default_machine).to_sym
14
+ @adapter = adapter || TransitionButtons.config.state_machine_adapter
15
+ @authorizer = authorizer || TransitionButtons.config.authorizer
16
+ end
17
+
18
+ # Events the state machine allows from the current state (guards applied).
19
+ def domain_events
20
+ @domain_events ||= Array(@adapter.available_events(@record, machine: @machine)).map(&:to_sym)
21
+ end
22
+
23
+ def domain_event?(event)
24
+ domain_events.include?(event.to_sym)
25
+ end
26
+
27
+ # The intersection the UI cares about: legal AND authorized for this user.
28
+ def permitted_events
29
+ domain_events.select { |event| authorized?(event) }
30
+ end
31
+
32
+ def permitted?(event)
33
+ domain_event?(event) && authorized?(event)
34
+ end
35
+
36
+ def current_state
37
+ @adapter.current_state(@record, machine: @machine)
38
+ end
39
+
40
+ # Fires the event. Returns the adapter's truthy/falsey result. Does NOT
41
+ # enforce authorization itself — callers (the controller) must check
42
+ # `permitted?` first; this keeps the security decision explicit at the
43
+ # boundary rather than buried in a side effect.
44
+ def fire(event)
45
+ @adapter.fire(@record, event.to_sym, machine: @machine)
46
+ end
47
+
48
+ private
49
+
50
+ def authorized?(event)
51
+ @authorizer.permitted?(user: @user, record: @record, event: event.to_sym, machine: @machine)
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,15 @@
1
+ require "rails/railtie"
2
+
3
+ module TransitionButtons
4
+ class Railtie < Rails::Railtie
5
+ initializer "transition_buttons.view_helper" do
6
+ ActiveSupport.on_load(:action_view) do
7
+ include TransitionButtons::ViewHelper
8
+ end
9
+ end
10
+
11
+ initializer "transition_buttons.routing" do
12
+ ActionDispatch::Routing::Mapper.include(TransitionButtons::Routing)
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,16 @@
1
+ module TransitionButtons
2
+ # Adds a `transitionable` helper to the routes DSL:
3
+ #
4
+ # resources :posts do
5
+ # transitionable # => POST /posts/:id/transition (transition_post)
6
+ # end
7
+ #
8
+ # Equivalent to writing `member { post :transition }`, but named so intent is
9
+ # obvious and so the route name stays consistent with what the view helper's
10
+ # `polymorphic_path([:transition, record])` expects.
11
+ module Routing
12
+ def transitionable
13
+ member { post :transition }
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,38 @@
1
+ module TransitionButtons
2
+ module StateMachineAdapters
3
+ # Adapter for the `state_machines` gem.
4
+ #
5
+ # state_machines prefixes its generated helpers with the machine's attribute
6
+ # name, so a machine declared as `state_machine :review_state` exposes
7
+ # `review_state_events`, `fire_review_state_event`, `review_state_name`, and
8
+ # `Klass.human_review_state_event_name`. We build those names from `machine`.
9
+ class StateMachines
10
+ # Events permitted by the machine's guards from the current state.
11
+ # `state_machines` evaluates if/unless guards here by default, so this is
12
+ # the domain-legal set, before authorization.
13
+ def available_events(record, machine:)
14
+ record.public_send("#{machine}_events")
15
+ end
16
+
17
+ def current_state(record, machine:)
18
+ record.public_send("#{machine}_name")
19
+ end
20
+
21
+ # Returns true/false (state_machines does not raise when an event is
22
+ # disallowed), letting the caller translate a false into an HTTP 422.
23
+ def fire(record, event, machine:)
24
+ record.public_send("fire_#{machine}_event", event)
25
+ end
26
+
27
+ def event_label(record, event, machine:)
28
+ humanizer = "human_#{machine}_event_name"
29
+ klass = record.class
30
+ if klass.respond_to?(humanizer)
31
+ klass.public_send(humanizer, event)
32
+ else
33
+ event.to_s.humanize
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,3 @@
1
+ module TransitionButtons
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,59 @@
1
+ module TransitionButtons
2
+ module ViewHelper
3
+ # Renders one button per event the current user may perform on `record`
4
+ # right now, each POSTing to the record's member `transition` route.
5
+ #
6
+ # <%= transition_buttons_for(@post) %>
7
+ # <%= transition_buttons_for(@post, machine: :review_state) %>
8
+ # <%= transition_buttons_for(@post, user: some_user, class: "btn") %>
9
+ #
10
+ # `user:` defaults to `current_user` when the view exposes it. Remaining
11
+ # keyword options are forwarded to each `button_to` as HTML options.
12
+ def transition_buttons_for(record, machine: nil, user: nil, **html_options)
13
+ resolver = transition_buttons_resolver(record, machine: machine, user: user)
14
+ adapter = TransitionButtons.config.state_machine_adapter
15
+ path = transition_buttons_path(record)
16
+
17
+ buttons = resolver.permitted_events.map do |event|
18
+ button_to(
19
+ adapter.event_label(record, event, machine: resolver.machine),
20
+ path,
21
+ method: :post,
22
+ params: {event: event, machine: resolver.machine},
23
+ **html_options
24
+ )
25
+ end
26
+
27
+ safe_join(buttons)
28
+ end
29
+
30
+ # The raw permitted-event list, for callers who want to render their own UI.
31
+ #
32
+ # <% available_events(@post).each do |event| %> ... <% end %>
33
+ def available_events(record, machine: nil, user: nil)
34
+ transition_buttons_resolver(record, machine: machine, user: user).permitted_events
35
+ end
36
+
37
+ private
38
+
39
+ def transition_buttons_resolver(record, machine:, user:)
40
+ EventResolver.new(
41
+ record: record,
42
+ user: user || transition_buttons_current_user,
43
+ machine: machine
44
+ )
45
+ end
46
+
47
+ def transition_buttons_current_user
48
+ return current_user if respond_to?(:current_user, true)
49
+
50
+ nil
51
+ end
52
+
53
+ # Resolves the record's member `transition` route, e.g. /posts/42/transition.
54
+ # Relies on the `transitionable` routing helper (a member POST :transition).
55
+ def transition_buttons_path(record)
56
+ polymorphic_path([:transition, record])
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,32 @@
1
+ require "transition_buttons/version"
2
+ require "transition_buttons/configuration"
3
+ require "transition_buttons/event_resolver"
4
+ require "transition_buttons/view_helper"
5
+ require "transition_buttons/controller"
6
+ require "transition_buttons/routing"
7
+ require "transition_buttons/railtie" if defined?(Rails::Railtie)
8
+
9
+ # Authorization-aware state machine transition buttons for Rails.
10
+ #
11
+ # Renders one button per event the current user may perform on a record (the
12
+ # intersection of "legal from the current state" and "authorized for this
13
+ # user"), each POSTing to a member `transition` route that re-checks both
14
+ # server-side before firing.
15
+ module TransitionButtons
16
+ class Error < StandardError; end
17
+
18
+ class << self
19
+ def config
20
+ @config ||= Configuration.new
21
+ end
22
+
23
+ def configure
24
+ yield config
25
+ end
26
+
27
+ # Test/reset hook.
28
+ def reset_config!
29
+ @config = Configuration.new
30
+ end
31
+ end
32
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: transition_buttons
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - First Draft
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: railties
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '7.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: actionview
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '7.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '7.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: state_machines
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0.6'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0.6'
54
+ - !ruby/object:Gem::Dependency
55
+ name: action_policy
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0.6'
61
+ type: :runtime
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0.6'
68
+ description: Render one button per event the current user may perform on a record,
69
+ each POSTing to a member transition route that re-authorizes server-side. Pluggable
70
+ state machine and authorization backends; ships with state_machines and ActionPolicy.
71
+ email:
72
+ - raghu@firstdraft.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - CHANGELOG.md
78
+ - LICENSE.txt
79
+ - README.md
80
+ - lib/transition_buttons.rb
81
+ - lib/transition_buttons/authorizers/action_policy.rb
82
+ - lib/transition_buttons/configuration.rb
83
+ - lib/transition_buttons/controller.rb
84
+ - lib/transition_buttons/event_resolver.rb
85
+ - lib/transition_buttons/railtie.rb
86
+ - lib/transition_buttons/routing.rb
87
+ - lib/transition_buttons/state_machine_adapters/state_machines.rb
88
+ - lib/transition_buttons/version.rb
89
+ - lib/transition_buttons/view_helper.rb
90
+ homepage: https://github.com/firstdraft/transition_buttons
91
+ licenses:
92
+ - MIT
93
+ metadata:
94
+ source_code_uri: https://github.com/firstdraft/transition_buttons
95
+ changelog_uri: https://github.com/firstdraft/transition_buttons/blob/main/CHANGELOG.md
96
+ rdoc_options: []
97
+ require_paths:
98
+ - lib
99
+ required_ruby_version: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '3.1'
104
+ required_rubygems_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ requirements: []
110
+ rubygems_version: 4.0.3
111
+ specification_version: 4
112
+ summary: Authorization-aware state machine transition buttons for Rails
113
+ test_files: []