ModularStateMachine
The ModularStateMachine is a Ruby module designed to integrate state machine behavior into ActiveRecord models. It's highly flexible and can be used to manage various states within your Rails application.
Installation
Include the ModularStateMachine module in your Gemfile:
gem 'modular_state_machine'Run the bundle command to install it:
bundle installUsage
Basic Usage
-
Integer Fields for States:
To use integer fields for states, add an integer column to your model and map states to integers.
add_column :applicants, :status, :integer, default: 0
-
Including the Module:
Include
ModularStateMachinein your ActiveRecord model.class Applicant < ApplicationRecord include ModularStateMachine end
-
Defining a State Machine:
Use
state_machine_forto define a state machine for a specific field.state_machine_for('Status', %w[Pending Active Approved Denied Archived])
-
Defining Scopes:
Define scopes for each state for easy querying.
scope :pending, -> { where(status: Status::Pending) }
Checking States
To check the state of an object, use the generated query methods.
applicant = Applicant.create(status: Applicant::Status::Active)
applicant.active? # => trueAdvanced Usage
-
Multiple State Machines:
You can define multiple state machines for different fields in the same model.
class User < ApplicationRecord include ModularStateMachine state_machine_for('Status', %w[Pending Active Approved Denied Archived]) state_machine_for('Role', %w[Admin Buyer Seller]) scope :pending, -> { where(status: Status::Pending) } # ... other scopes end
Usage:
applicant = Applicant.last applicant.pending? # => true applicant.admin? # => true applicant.buyer? #=> false
Examples
-
Applicant Model with State Machine:
class Applicant < ApplicationRecord include ModularStateMachine state_machine_for('Status', %w[Pending Active Approved Denied Archived]) scope :pending, -> { where(status: Status::Pending) } # ... other scopes end
Usage:
applicant = Applicant.new(status: Applicant::Status::Pending) applicant.pending? # => true applicant.status = Applicant::Status::Denied applicant.pending? # => false applicant.denied? #=> true
-
Exam Ruby Class with a State Machines:
class ExamClass include ModularStateMachine attr_accessor :category state_machine_for('Category', ['PeerReviewed', 'NonPeerReviewed', 'CaseStudy']) # ... additional configurations end
Usage:
exam = ExamClass.new exam.category = 'PeerReviewed' exam.peer_reviewed? # => true
Contact
In case you will have any query reach out to me on azan.butt.dev@gmail.com
Linkedin: https://www.linkedin.com/in/azandev/