Skip to content

Instantly share code, notes, and snippets.

@sunaot
sunaot / exception_in_ruby.md
Created March 10, 2014 11:31
Ruby で Exception

Ruby でアプリケーション例外をつくるときの作り方。

begin
  # 通常の処理
rescue SomeErrorException => e
  # Exception から継承したクラスや StandardError から継承したクラスを指定で受ける
rescue => e # StandardError
  # 継承木に StandardError がいるクラスのみひっかかる
else
@sunaot
sunaot / capybara_win.md
Created April 10, 2014 10:30
capybara on windows

制約フレームワークを書かないと連載させてもらえない Web 雑誌があるようなので、昨日こんなの書いてた。 静的解析もできないし、ドキュメンテーションにも活きないので各方面の識者から怒られそうだが {} で書けるという見た目の点で許してほしい。

あとはつっこまれるとしたら、継承したときに事前条件、事後条件が強化される/緩和されるのあたり。全部やると大変なんすよ。invariant もないですね (method_added でイベントフックしてすべてのメソッドコールへ prepend かぶせるとかすればできるかな)。

class BeerLover
  extend Contracts
  attr_accessor :age
@sunaot
sunaot / spock-like.rb
Last active August 29, 2015 14:07
spock ぽい何かの Ruby での習作
module Ruby
module Spock
def spec(description, definition = nil, &proc_definition)
raise ArgumentError if [ definition, proc_definition ].all? {|d| d.nil? }
if definition.nil?
spec_runner(description, proc_definition)
else
spec_runner(description, definition)
end
end
@sunaot
sunaot / spock-like-spec.rb
Created October 14, 2014 16:05
Spock のようななにかを Ruby で。の仮実装。これは spec 側。実装は https://gist.github.com/sunaot/9efce49897e3dbf98fca にあります。
class Foo
extend Ruby::Spock
spec 'maximum of two numbers', ->(*) {
expect ->(a, b, c) { [a, b].max == c }
where [
# a | b | c
[ 1 , 3 , 3 ],
[ 7 , 4 , 4 ],
[ 0 , 0 , 0 ],
@sunaot
sunaot / swap_closure_local_variable.rb
Created October 14, 2014 17:50
Ruby でクロージャのローカル変数を差し替え (たかのように錯覚させる) トリック
def e &blk
s = Struct.new(:a,:b,:c).new(1,2,3)
s.instance_eval(&blk)
end
def foo
e { a + b + c }
end
puts foo #=> 6
@sunaot
sunaot / keyword.rb
Last active August 29, 2015 14:10
キーワード引数で引数の委譲や再定義ってどうやるの?って質問したら答えを教えてもらったよ
##
# 知りたかったこと
def foo(a: 1, b: 2, c: 3, d: 4)
p a, b, c, d
end
# 1. bar の引数定義を a~d のキーワード引数として foo へすべて委譲したい
# 2. bar の引数定義を a~d のキーワード引数とさらに e: 5 を追加したい
def bar( ??? )
class Injectee
def hello
puts :hello
end
end
module DI
class Injector
def initialize(module_object)
@module = module_object
@sunaot
sunaot / comment.md
Created January 13, 2015 07:30
shared_example ぇぇぇ

たとえば、subject でこのように書けて、

subject { model.errors }
it { is_expected.to be > 0 }

これを DRY にしたくて

@sunaot
sunaot / learning_oop.md
Last active August 29, 2015 14:14
オブジェクト指向プログラミングの設計について学ぶためのリソースあれこれ