Created
April 7, 2020 18:33
-
-
Save nathanpalmer/c4a37d254f8fc3d41c43685fc31dbd11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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