Created
March 25, 2014 16:43
-
-
Save esmevane/9766011 to your computer and use it in GitHub Desktop.
[ Strategy Pattern / Factory Pattern / MiniTest ] - Example strategy + factory use, with light minitest integration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'minitest/autorun' | |
| require 'minitest/pride' | |
| class ListStrategy | |
| attr_reader :dates, :foods | |
| def initialize list | |
| foods = list.map { |item| item.keys.map(&:to_s) } | |
| @dates = list.map { |item| item.fetch(:date) } | |
| @foods = foods.flatten.uniq - ['date'] | |
| end | |
| end | |
| class HashStrategy | |
| attr_reader :dates, :foods | |
| def initialize hash | |
| @dates = hash.fetch(:dates) | |
| @foods = hash.fetch(:foods) | |
| end | |
| end | |
| class SnapshotFactory | |
| attr_reader :strategy | |
| def initialize strategy, *raw_input | |
| @strategy = strategy.new(*raw_input) | |
| end | |
| def create | |
| Snapshot.build do |snapshot| | |
| snapshot.add_dates *strategy.dates | |
| snapshot.add_foods *strategy.foods | |
| end | |
| end | |
| def self.create strategy, *raw_input | |
| new(strategy, *raw_input).create | |
| end | |
| end | |
| class Snapshot | |
| attr_reader :dates, :foods | |
| def initialize | |
| @dates = [] | |
| @foods = [] | |
| end | |
| def add_dates *list | |
| @dates = (dates + list).uniq.sort | |
| end | |
| def add_foods *list | |
| @foods = (foods + list).uniq.sort | |
| end | |
| def == other | |
| dates == other.dates && foods == other.foods | |
| end | |
| def self.build | |
| snapshot = new | |
| yield snapshot | |
| snapshot | |
| end | |
| end | |
| describe "SnapshotFactory" do | |
| let(:dates) { [ 12341512515, 15082501285 ] } | |
| let(:foods) { [ 'burrito', 'papaya' ] } | |
| let(:hash) { { dates: dates, foods: foods } } | |
| let(:list) do | |
| [ | |
| { date: 12341512515, burrito: true }, | |
| { date: 15082501285, papaya: true } | |
| ] | |
| end | |
| let(:example_snapshot) do | |
| Snapshot.build do |snapshot| | |
| snapshot.add_dates *dates | |
| snapshot.add_foods *foods | |
| end | |
| end | |
| describe 'List input & Strategy' do | |
| let(:snapshot) { SnapshotFactory.create(ListStrategy, list) } | |
| subject { snapshot } | |
| it { subject.must_equal example_snapshot } | |
| end | |
| describe 'Hash input & Strategy' do | |
| let(:snapshot) { SnapshotFactory.create(HashStrategy, hash) } | |
| subject { snapshot } | |
| it { subject.must_equal example_snapshot } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment