Skip to content

Instantly share code, notes, and snippets.

@laser
laser / module.rb
Created January 27, 2014 20:05
module as namespace
# app/utils/calculator.rb
module StatelessCalculator
def add(x, y)
x + y
end
module_function :add
end
@laser
laser / less_state.rb
Created January 26, 2014 23:04
RSS Importer - less state
class RssImporter
def self.import(articles)
articles.map do |article|
RssContent.create { url: article.url, text: article.body }
end
end
end
# somewhere in your codebase...
imported = RssImporter.import a_bunch_of_rss_content
@laser
laser / bad.rb
Last active January 4, 2016 15:28
more bad
# our first import
importer = RssImporter.new
importer.articles = a_bunch_of_rss_content
importer.import
imported = importer.result
# second import, same instance of RssImporter
importer.articles = other_rss_content
importer.result # same value as "imported" on line 5
@laser
laser / unnecessarily.rb
Last active January 4, 2016 15:19
unnecessarily introducing mutable state
class RssImporter
attr_writer :articles
attr_reader :result
def import
@result = articles.map do |article|
RssContent.create { url: article.url, text: article.body }
end
end
end
@laser
laser / service.rb
Last active January 4, 2016 10:19
service.rb
# app/utils/calculator.rb
class StatelessCalculator
def self.add(x, y)
x + y
end
# ...subtract, divide, multiply, etc.
end
# app/services/calculation_isolate.rb
@laser
laser / s3_prunable_after.rb
Last active January 4, 2016 10:19
prunable b
# app/util/prunable.rb
class Prunable
def self.from_assets(assets)
assets.select &method(:is_prunable?)
end
def self.is_prunable?(asset)
asset.created_at < Date.today - 30
end
end
@laser
laser / s3_pruner_before.rb
Created January 24, 2014 22:12
s3 pruner a
class S3FilePruner < JobProcessor
def process_job
Images.all.select do |image|
image.created_at < Date.today - 30
end.each do |image|
S3Object.delete image.s3_object_name, image.s3_bucket_name
image.destroy
end
end
end
@laser
laser / table_based.rb
Last active January 4, 2016 09:39
Table based testing
# Account = Struct.new(:id, :last_active)
describe 'pruning expired accounts' do
let(:f) {
# an account factory
lambda do |id, last_active=Date.today|
Account.new(id, last_active)
end
}
@laser
laser / array_combiner.rb
Last active January 4, 2016 09:39
array combiner
# Account = Struct.new(:id, :last_active)
describe 'pruning expired accounts' do
let(:acc1) { Account.new(1, Date.today) }
let(:acc2) { Account.new(2, Date.today) }
let(:acc3) { Account.new(3, Date.today) }
describe 'when the first account is expired' do
let(:acc1) { Account.new(1, Date.today - 45) }
# app/controllers/calculation.rb
def create
req = ActiveSupport::JSON.decode(request.body)
calculator = StatefulCalculator.new
# to_crunch => [[1, 2, 3], [9, 10, 11]]
@sums = req["to_crunch"].map do |nums|
NumberCruncher.new(calculator).crunch(nums)