Skip to content

Instantly share code, notes, and snippets.

@laser
laser / _repository.rb
Last active January 3, 2016 19:49
Persisting Calculator
# a fake repository
class Repository
def self.save_calculation(op, n1, n2, result)
puts "just saved #{op}, #{n1}, #{n2}, #{result}"
end
end
@laser
laser / higher_order_function.rb
Last active January 3, 2016 20:29
Higher-order function
# implemented in the controller action, result from the
# calculator operation is passed to the Repository
# app/controllers/calculation.rb
def create
h = ActiveSupport::JSON.decode(request.body)
fx = lambda do |op, mod, repo|
lambda do |x, y|
result = mod.method(op.to_sym).to_proc[x, y]
@laser
laser / function_calc.rb
Last active January 4, 2016 00:39
Functional OO Calculator
class StatefulCalculator
def initialize(total)
@total = total
end
def add(x)
StatefulCalculator.new(@total + x)
end
def sub(x)
@laser
laser / foo_spec_bug.rb
Last active January 4, 2016 03:19
foo.rb spec - with bug
require_relative '../foo'
describe StatefulCalculator do
before(:all) do
@subject = StatefulCalculator.new
end
it 'should add some numbers' do
expect(@subject.add(5).add(3).add(10).result).to eq(18)
end
@laser
laser / asset.rb
Last active January 4, 2016 03:59
blar.rb
module Prunable
def from_assets(assets)
assets.select &method(:is_prunable?)
end
def is_prunable?(asset)
asset.created_at < Date.today - 30
end
module_function from_assets, is_prunable?
@laser
laser / pure.rb
Last active January 4, 2016 04:19
Pure Functions
# lambda is impure: mutates shared state (the fruits hash)
fruits = {}
hashify = lambda do |fruit|
fruits[fruit] = fruit
end
["apple", "pear"].each &hashify
# lambda is pure: operates only on its arguments
to_nv_pair = lambda do |fruit|
[fruit, fruit]
@laser
laser / stateful.rb
Created January 22, 2014 21:30
Stateful Calculator
class StatefulCalculator
def initialize
@total = 0
end
def add(x)
@total += x
self
end
@laser
laser / stateless.rb
Created January 22, 2014 21:30
Stateless Calculator
module StatelessCalculator
def add(x, y)
x + y
end
def div(num, denom)
num / denom
end
module_function :add, :div
@laser
laser / statefultest_a.rb
Created January 22, 2014 21:31
Stateful Test A
describe StatefulCalculator do
before(:all) do
@subject = StatefulCalculator.new
end
it 'should add some numbers' do
expect(@subject.add(5).add(3).add(10).result).to eq(18)
end
end
@laser
laser / statefultest_b.rb
Created January 22, 2014 21:32
Stateful Test B
describe StatefulCalculator do
before(:all) do
@subject = StatefulCalculator.new
end
it 'should add some numbers' do
expect(@subject.add(5).add(3).add(10).result).to eq(18)
end
it 'should divide some numbers' do