Skip to content

Instantly share code, notes, and snippets.

@jonstorer
Last active October 19, 2016 13:48
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 jonstorer/ca3a6ae2c95a6cbf38b6132f7d713d5f to your computer and use it in GitHub Desktop.
Save jonstorer/ca3a6ae2c95a6cbf38b6132f7d713d5f to your computer and use it in GitHub Desktop.
DI in Ruby
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
self << class
def inject_dependecy(*args)
options = args.last.is_a?(Hash) args.pop || {}
injectable_dependencies = args
injectable_dependencies.each do |injectable_dependency|
define_method injectable_dependency do
$service.get(injectable_dependency);
end
before_action injectable_dependency, options
end
end
def request_entity(entity_name, options = {})
define_method entity_name do
@entity_name ||= entity_name.stringify.constantize.new(params)
end
define_method "validate_#{entity_name}" do
entity_name.validate!
end
before_action "validate_#{entity_name}", options
end
end
end
class Service
def initialize
@services = {}
end
def get(service_name)
@services[service_name] ||= service_name.stringify.constantize.new
end
end
$services = Service.new
class WidgetsController < ApplicationController
inject_dependecy :widget_service, :only => :index
request_entity :widget_search_request_entity, :only => :index
def index
widget_service.search(widget_search_request_entity)
end
end
@jonstorer
Copy link
Author

I'm not sure where the methods in the Application Controller would actually live. Don't worry about that for now, just pay attention to what I'm trying to do in the controller.

@tripleentendre
Copy link

I like it. This is an ignorant question but can ruby take care of mapping the request params in the hash to the properties in the request entity? That would be cool...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment