Skip to content

Instantly share code, notes, and snippets.

@bestie
Last active June 21, 2016 08:57
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 bestie/7074552 to your computer and use it in GitHub Desktop.
Save bestie/7074552 to your computer and use it in GitHub Desktop.
"Improve your code with dependency injection" code samples
class ApplicationController < ActionController::Base
private
def app
APP
end
end
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
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
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