Last active
June 21, 2016 08:57
-
-
Save bestie/7074552 to your computer and use it in GitHub Desktop.
"Improve your code with dependency injection" code samples
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 ApplicationController < ActionController::Base | |
private | |
def app | |
APP | |
end | |
end |
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 ComplexProduceSearch | |
def initialize(dependencies) | |
# Now this can search even vegetables! | |
@type = dependencies.fetch(:type) | |
end | |
def results(args) | |
@params = args.fetch(:params) | |
@scope = args.fetch(:scope, :all) | |
type.public_send(scope).where(orm_friendly_params) | |
end | |
private | |
attr_reader :type, :params, :scope | |
def orm_friendly_params | |
# lots of complex logic | |
end | |
end |
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 FruitApp | |
def fruit_search | |
ComplexProduceSearch.new( | |
type: Fruit, | |
) | |
end | |
def vegetable_search | |
ComplexProduceSearch.new( | |
type: Vegetable, | |
) | |
end | |
# Potentially one method per controller action | |
end | |
APP = FruitApp.new |
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 FruitsController < ApplicationController | |
def in_season_search | |
@results = app.fruit_search.call( | |
scope: :in_season, | |
params: params, | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment