Last active
December 16, 2015 21:59
-
-
Save bestie/5504108 to your computer and use it in GitHub Desktop.
Using service layer / service locator pattern with Rails.
This file contains 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 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