Last active
November 24, 2015 17:37
-
-
Save RasPhilCo/fc1c08bab89000fa4ebc to your computer and use it in GitHub Desktop.
POODR, Chp 8 Combining Objects with Composition, Sandi Metz
This file contains 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
class Bicycle | |
attr_reader :size, :parts | |
def initialize(args={}) | |
@size = args[:size] | |
@parts = args[:parts] | |
end | |
def spares | |
parts.spares | |
end | |
end | |
require 'forwardable' | |
class Parts | |
extend Forwardable | |
def_delegators :@parts, :size, :each | |
include Enumerable | |
def initialize(parts) | |
@parts = parts | |
end | |
def spares | |
select {|part| part.needs_spare} | |
end | |
end | |
require 'ostruct' | |
module PartsFactory | |
def self.build(config, parts_class = Parts) | |
parts_class.new( | |
config.collect {|part_config| | |
create_part(part_config)}) | |
end | |
def self.create_part(part_config) | |
OpenStruct.new( | |
name: part_config[0], | |
description: part_config[1], | |
needs_spare: part_config.fetch(2, true)) | |
end | |
end | |
road_config = | |
[['chain', '10-speed'], | |
['tire_size', '23'], | |
['tape_color', 'red']] | |
mountain_config = | |
[['chain', '10-speed'], | |
['tire_size', '2.1'], | |
['front_shock', 'Manitou', false], | |
['rear_shock', 'Fox']] | |
road_bike = | |
Bicycle.new( | |
size: 'L', | |
parts: PartsFactory.build(road_config)) | |
road_bike.spares | |
# -> [#<OpenStruct name="chain", etc ... | |
mountain_bike = | |
Bicycle.new( | |
size: 'L', | |
parts: PartsFactory.build(mountain_config)) | |
mountain_bike.spares | |
# -> [#<OpenStruct name="chain", etc ... |
Author
RasPhilCo
commented
Nov 21, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment