6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

組み合わせを展開するcombination-extractorをつくった

Last updated at Posted at 2016-03-28

組み合わせを展開するcombination-extractorというRubygemを作りました

実行方法
# こんな感じのハッシュを渡すと、
# {
#   fruit: ['apple', 'orange'],
#   city: ['NewYork', 'London', 'Tokyo']
# }

CombinationExtractor.extract({fruit: ['apple', 'orange'], city: ['NewYork', 'London', 'Tokyo']})
=> [{:fruit=>"apple", :city=>"NewYork"}, {:fruit=>"apple", :city=>"London"}, {:fruit=>"apple", :city=>"Tokyo"},
    {:fruit=>"orange", :city=>"NewYork"}, {:fruit=>"orange", :city=>"London"}, {:fruit=>"orange", :city=>"Tokyo"}]

# こんな感じに展開してくれます
# [
#   {:fruit=>"apple", :city=>"NewYork"},
#   {:fruit=>"apple", :city=>"London"},
#   {:fruit=>"apple", :city=>"Tokyo"},
#   {:fruit=>"orange", :city=>"NewYork"},
#   {:fruit=>"orange", :city=>"London"},
#   {:fruit=>"orange", :city=>"Tokyo"}
# ]

何が嬉しいのか

Rspecで同じパターンの組み合わせで一部だけ変わるテストを書く時に、contextの入れ子が続いてつらかったので、context-extractorをつくりました。

def example_similar_to(user_hash)
  user_hash[:birthday] == Time.new(1988, 12, 30) &&
    user_hash[:gender] == :male
end

describe 'About example example_similar_to method' do
  let(:nickname) { nil }
  let(:gender) { nil }
  let(:birthday) { nil }
  let(:user) { { nickname: nickname, gender: gender, birthday: birthday } }

  user_condition = {
    nickname: ['John', 'Ken', 'Jessie'],
    gender: [:female, :male],
    birthday: [Time.new(1988, 12, 30), Time.now]
  }
  # Get 2*2*3 = 12 patterns
  pattern_list = CombinationExtractor.extract(user_condition)

  pattern_list.each do |pattern|
    describe "user who is #{pattern.to_s}" do
      # NOTE: Set pattern to lazy evaluated variable
      pattern.each { |key, value| let(key) { value } }

      should_value = pattern[:gender] == :male && pattern[:birthday] == Time.new(1988, 12, 30)
      it "should return #{should_value}" do
        expect(example_similar_to(user)).to eq(should_value)
      end
    end
  end
end

Rspecに関してはもっと良いやり方が他にありそうな気もするのですが、パッと探して見つからなかったので、とりあえずはたまにこのように展開するコードを書いています。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?