Skip to content

Instantly share code, notes, and snippets.

@laser
laser / stateless_test_a.rb
Created January 22, 2014 21:32
Stateless Test
describe StatelessCalculator do
it 'should add some numbers' do
expect(StatelessCalculator.add(10, StatelessCalculator.add(5, 3))).to eq(18)
end
it 'should divide some numbers' do
expect(StatelessCalculator.div(10, 2)).to eq(5)
end
end
@laser
laser / multi_unsafe.rb
Created January 22, 2014 21:33
Multithread unsafe
def add_range_unsafe
c = StatefulCalculator.new
threads = (1..256).each_slice(16).map do |range|
Thread.new do
range.each { |n| c.add n }
end
end
threads.map(&:join)
@laser
laser / multi_safe.rb
Created January 22, 2014 21:33
Multithread safe
def add_range_safe
threads = (1..256).each_slice(16).map do |range|
Thread.new do
Thread.current[:sum] = range.inject(0) do |memo, n|
StatelessCalculator.add memo, n
end
end
end
result = threads.map { |t| t.join[:sum] } .reduce(:+)
@laser
laser / rails.rb
Created January 22, 2014 21:34
Real World Rails
# app/services/calculation_service.rb
class CalculationService
def initialize(repository)
@repository = repository
end
def calculate(operation, x, y)
result = StatelessCalculator.send operation, x, y
@repository.save_calculation operation, x, y, result
result
@laser
laser / cruncher.rb
Last active January 4, 2016 09:19
number cruncher
class NumberCruncher
def initialize(calculator)
@calculator = calculator
end
def crunch(array_of_numbers)
@reduction ||= array_of_numbers.each do |number|
@calculator.add number
end
# 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)
@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) }
@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 / 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 / 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