Skip to content

Instantly share code, notes, and snippets.

View cmorss's full-sized avatar

Charlie Morss cmorss

View GitHub Profile
@cmorss
cmorss / stateful.rb
Created April 8, 2020 22:55
ActiveRecord state machine
module Instructify
# Mark an ActiveRecord model as having a state machine. Requires a
# string attribute called `state`. To set the default state for a
# class, set a default column value for `state` in the database.
#
# Use Symbols for all keys and values in state definitions.
module Stateful
ANY = Object.new
has_one :intro_progress, inverse_of: :skill_progress, autosave: true, required: false, dependent: :destroy
has_one :video_challenge_progress, inverse_of: :skill_progress, autosave: true, required: false, dependent: :destroy
has_many :step_progresses, -> { includes(:step).order(:order) }, inverse_of: :skill_progress, autosave: true,
dependent: :destroy
with assessment_block_index as (
select
entity_key as assessment_block_key,
parent_key as step_key
from entity_indices
where entity_type = 'AssessmentBlock'
),
step_index as (
select
entity_key as step_key,
@cmorss
cmorss / stateful.rb
Created May 19, 2021 22:29
Statemachine
# Mark an ActiveRecord model as having a state machine.
# The state of the model defaults to being stored on an attribute
# called `state` or can be specified via the `column` arg to
# the `stateful` call. To set the default state for a
# class, set a default column value for `state` in the database
# or use `initial: true` when defining the initial state.
#
# Use Symbols for all keys and values in state definitions.
module Stateful
@cmorss
cmorss / stateful_spec.rb
Created May 19, 2021 22:29
Stateful specs
require 'rails_helper'
RSpec.describe Stateful do
let(:model_class) do
Struct.new(:status, :saved, :scopes, :running_at, :finished_at, :finished_count, :privileged) do
include Stateful
def self.scope(*args)
define_singleton_method(args.first) {}
end