Skip to content

Instantly share code, notes, and snippets.

View richmolj's full-sized avatar

Lee Richmond richmolj

View GitHub Profile
# not real code
module Rack
class Director
def call(env)
@request = Rack::Request.new(env)
status, headers, body = @app.call(env)
@response = Rack::Response.new(body, status, headers)
if authenticated?
# inject toolbar
end
class MyUploader < CarrierWave::Uploader::Base
def store_dir
Configuration[:store_dir]
end
end
class Delay
def by
# complex logic
result = yield
# complex logic
result
end
end
class Post
class Post
def publish
self.published_at = Delay.by(Configuration[:delay_time])
save
end
end
class HttpRequestWrapperGem
def request(uri)
config.backend.get uri
end
end
HttpRequestWrapperGem.configure do |c|
c.backend = SearchVersion2.new
end
@richmolj
richmolj / gist:5832296
Last active December 18, 2015 19:19
Lee and Lou's DI Guidelines
1. If something is simple and <30%* likely it will be changed, don't DI for DI's sake:
  • This is probably a sliding scale depending on the scenario. 30% is obviously a loose guideline and serves as a jumping-off point. Just know it's not 90%.

Example 1 (Encrypter)
Example 2 (simple published_at)

2. When something is <30% likely to change, but getting complicated:

Add a class if this is a separate responsibility:

# when running cron jobs
module PutsOverride
def puts(*stmt)
if Configuration[:redirect_puts]
# write the stmt to custom log file for this cron
else
super(*stmt)
end
end
around_filter :set_time_zone
def set_time_zone
begin
old_time_zone = Time.zone
Time.zone = current_user.time_zone if logged_in?
yield
ensure
Time.zone = old_time_zone
end
class Post
def initialize(backend)
@backend = backend
end
def all
@backend.all
end
end
Post.new(DB::Post.new)
class Post
def all
Config[:backend].all
end
end