Last active
October 19, 2016 13:48
-
-
Save jonstorer/ca3a6ae2c95a6cbf38b6132f7d713d5f to your computer and use it in GitHub Desktop.
DI in Ruby
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 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 |
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 Service | |
def initialize | |
@services = {} | |
end | |
def get(service_name) | |
@services[service_name] ||= service_name.stringify.constantize.new | |
end | |
end | |
$services = Service.new |
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...