Skip to content

Instantly share code, notes, and snippets.

@BenMorganIO
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save BenMorganIO/14b7166fc0780b8fccb4 to your computer and use it in GitHub Desktop.

Select an option

Save BenMorganIO/14b7166fc0780b8fccb4 to your computer and use it in GitHub Desktop.
ApplicationService for controllers
module ApplicationService
extend ActiveSupport::Concern
included do
attr_accessor :request
def self.call(*args)
# The last caller should be a controller and by using
# the binding_of_caller gem, we can grab that instance.
ctrl = binding.of_caller(1)
# Lets pass the request and response objects and methods
# over into the service for it to use. This will allow
# us access to methods such as `redirect_to` and `flash`.
request = ctrl.eval "request"
_request = ctrl.eval "@_request"
_response = ctrl.eval "@_response"
# Create a new object of the service and pass in the
# request and response objects for it to be aware of.
# Then, we find a method called `#call` and call it.
new(request, _request, _response).call(*args)
end
# Create the new object and make sure it is aware of
# the request and response objects.
def initialize(request, _request, _response)
@request = request
@_request = _request
@_response = _response
end
# All services are expected to have a `#call` method,
# therefore if none are found, then fail with a
# NotImplementedError
def call(*)
fail NotImplementedError
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment