Last active
August 29, 2015 14:20
-
-
Save TheKidCoder/e89d2193ceb344db21ab to your computer and use it in GitHub Desktop.
Example Controller Service Object
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
module Workflows | |
class Base | |
attr_reader :errors | |
def self.call(*args) | |
new(*args).call | |
end | |
def initialize(params) | |
@params = __params(params) | |
end | |
def call | |
raise NotImplementedError | |
end | |
private | |
def __params(p) | |
p.respond_to?(:to_unsafe_hash) ? p.to_unsafe_hash.deep_symbolize_keys : p.deep_symbolize_keys | |
end | |
end | |
end |
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
module Workflows | |
module Events | |
module Common | |
def event_params | |
@params.slice(:active, :venue_id, :name, :featured, :description, :details, :seating, :seating_chart_id) | |
end | |
end | |
end | |
end |
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
module Workflows | |
module Events | |
class Create < Workflows::Base | |
include Workflows::Events::Common | |
attr_accessor :event | |
def call | |
ActiveRecord::Base.transaction {create} | |
rescue ActiveRecord::RecordInvalid => exception | |
@errors = @event.errors | |
return false | |
end | |
def create | |
@event = Event.create!(event_params) | |
return @event.valid? && create_venue && create_users | |
end | |
private | |
def create_venue | |
@event.create_venue!(venue_params) | |
end | |
def create_users | |
@event.users.create!(user_params) | |
end | |
end | |
end | |
end |
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
class EventsController < ApplicationController | |
def create | |
transactor = Workflows::Events::Create.new(params) | |
if transactor.call | |
render json: transactor.event | |
else | |
render json: transactor.errors | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment