Skip to content

Instantly share code, notes, and snippets.

@bestie
Last active December 16, 2015 21:59
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 bestie/5504108 to your computer and use it in GitHub Desktop.
Save bestie/5504108 to your computer and use it in GitHub Desktop.
Using service layer / service locator pattern with Rails.
class ThingsController < ApplicationController
def create
result = service.for(:create_thing).call(current_user, params) # I prefer to pass self
respond_with(result) # then the service can call render, respond_with or a method you write
end
private
def service
ServiceLocator.new
end
end
class ServiceLocator
def for(name)
map.fetch(name)
end
private
def map
# This could be loaded from a yaml file or you could infer the class name from the name.
# Here you are implementing YOUR app's routing independent of delivery (HTTP)
{
:create_thing => CreateThing.new(dependencies)
}
end
def dependencies
# pass in dependencies / configuration
end
end
class CreateThing
def initialize(dependencies = {})
end
# always use a call method unless you have a good reason not to.
def call(current_user, params)
# create a thing
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment