Last active
August 29, 2015 14:20
-
-
Save razorcd/3722a9e8683f416c0aed to your computer and use it in GitHub Desktop.
Class Specialisations (Composition + Dependency injection) by Sandi Metz
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
# Class Specialisations (Composition + Dependency injection) | |
class House | |
DATA = [1,2,3,4,5,6] | |
attr_reader :data | |
def initialize(orderer: DefaultOrderer.new, formatter: DefaultFormatter.new) | |
# @data = formatter.format(orderer.order(DATA)) | |
formatted_data = formatter.format(DATA) | |
@data = orderer.order(formatted_data) | |
end | |
end | |
class DefaultOrderer | |
def order(data) | |
data | |
end | |
end | |
class DefaultFormatter | |
def format(data) | |
data | |
end | |
end | |
class RandomOrderer | |
def order(data) | |
data.shuffle | |
end | |
end | |
class EchoFormatter | |
def format(data) | |
data.zip(data).flatten | |
end | |
end | |
h = House.new | |
puts "h: #{h.data}" | |
h_rand = House.new(orderer: RandomOrderer.new) | |
puts "h_rand: #{h_rand.data}" | |
h_echo = House.new(formatter: EchoFormatter.new) | |
puts "h_echo: #{h_echo.data}" | |
h_rand_echo = House.new(orderer: RandomOrderer.new, formatter: EchoFormatter.new) | |
puts "h_rand_echo: #{h_rand_echo.data}" | |
#RESULT: | |
# razor@razor-VM:~/RUBY/dependencies$ ruby house.rb | |
# h: [1, 2, 3, 4, 5, 6] | |
# h_rand: [6, 3, 5, 2, 1, 4] | |
# h_echo: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6] | |
# h_rand_echo: [2, 1, 5, 3, 6, 2, 4, 3, 4, 6, 5, 1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment