Skip to content

Instantly share code, notes, and snippets.

View richmolj's full-sized avatar

Lee Richmond richmolj

View GitHub Profile
@richmolj
richmolj / gist:5794539
Last active December 18, 2015 14:08
Dependency Injection
# Everyone should like some amount of Dependency Injection in Ruby.
# How much you like usually depends on how much importance you place on
# two competing values:
#
# 1. Build extensibly, loosely coupled components so you can properly
# adapt as your application scales. And things that start simple usually
# end up complex, so keep a solid foundation (read: solid OOP foundation
# in these concepts early on).
#
# and
class Post
def search(keywords)
search = Sunspot.search(Post) do
fulltext keywords
order_by :published_at, :desc if Configuration.post_ordering?
end
end
CustomAlarmHandler.new(:post_search).raise('empty!') if search.results.empty?
StatsCollector.register_event(:post_search, keywords)
search.results
class Post
def initialize(searcher, alarm_handler, stats_collector, should_order_posts)
@searcher = searcher
@alarm_handler = alarm_handler
@status_collector = stats_collector
@should_order_posts = should_order_posts
end
def search(keywords)
@richmolj
richmolj / gist:5815196
Last active December 18, 2015 16:59
Back and forth with Lou
@richmolj
richmolj / gist:5822934
Last active December 18, 2015 17:59
Step-by-step refactoring
# First iteration
class Post
def publish
self.published_at = Time.now
save
end
end
# Second iteration
# published_at logic gets more complex
class Story
def attributes
{
:id => Encrypter.encrypt(self.suid)
}
end
end
# DI
class Comment < ActiveRecord::Base
end
class Photo < ActiveRecord::Base
end
class Post
def initialize(comment_repository, photo_repository)
class Post
def publish
self.published_at = Time.now
save
end
end
# Do this when PublishTime implements whacky logic
class Post
def publish
publish_time = PublishTime.new
self.published_at = publish_time.stamp
save
end
end
# This example is pretty overkill, just illustrating the concept
module Delayable
def delay(attribute, opts)
# maybe we do additional timing stuff here, like UTC
send("#{attribute}=", opts[:by].from_now)
end
end
class Post