Skip to content

Instantly share code, notes, and snippets.

@nathanpalmer
Created April 7, 2020 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanpalmer/c4a37d254f8fc3d41c43685fc31dbd11 to your computer and use it in GitHub Desktop.
Save nathanpalmer/c4a37d254f8fc3d41c43685fc31dbd11 to your computer and use it in GitHub Desktop.
require 'conderaction'
class Model
def save
end
end
class Changeset
attr_reader :model, :context
def initialize(klass, model, context)
@klass = klass
@model = model
@context = OpenStruct.new(context)
@context.api_role = :unknown if @context.api_role.blank?
@context.persisted = false
end
def persist
@klass.persist(model, context)
@context.persisted = true
self
end
def persisted?
@context.persisted == true
end
def run(method_name, options = {})
@klass.send(method_name)
self
end
end
class Action
include DCI::Context
def perform(*args)
puts " - Action::perform"
data = changeset(*args)
ActiveRecord::Base.transaction do
change(data)
unless data.persisted?
fail "Did not create"
end
end
data.model
end
def changeset(attributes, context = {})
model = Model.new
Changeset.new(self, model, context)
end
def change(data)
data.persist
end
def persist(_model, _context)
fail "You must override the persist method in the model action."
end
end
class CreateAction < Action
def perform(*_args)
puts " - CreateAction::perform"
super
end
def persist(model, _context)
puts " - CreateAction::persist"
model.save
end
end
class ModelAction < CreateAction
def perform(*_args)
puts " - ModelAction::perform"
super
end
def model_method
puts " - ModelAction::model_method"
end
def change(data)
data
.run(:model_method)
.persist
end
end
class UserModelAction < ModelAction
def perform(*_args)
puts "UserModelAction::perform"
super
end
def user_method
puts " - UserModelAction::user_method"
end
def another_method
puts " - UserModelAction::another_method"
end
def change(data)
data
.run(:user_method)
super
.run(:another_method)
end
end
UserModelAction.perform(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment