Skip to content

Instantly share code, notes, and snippets.

@meaganewaller
Created January 1, 2015 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meaganewaller/6261ea7ea69254252c1a to your computer and use it in GitHub Desktop.
Save meaganewaller/6261ea7ea69254252c1a to your computer and use it in GitHub Desktop.
the adapter pattern
class BritishTextObjectAdapter < TextObject
def initialize(bto)
@bto = bto
end
def text
return @bto.string
end
def size_inches
return @bto.size_mm / 25.4
end
def color
return @bto.colour
end
end
class BritishTextObject
attr_reader :string, :size_mm, :colour
# ....
end
reader = File.open('foo.txt')
writer = File.open('foo.encrypted', 'w')
encrypter = Encrypter.new('the secret key')
encrypter.encrypt(reader, writer)
encrypter = Encrypter.new('OURSTRING')
reader = StringIOAdapter.new('This is our string')
writer = File.open('out.txt', 'w')
encrypter.encrpyt(reader, writer)
# encrypter.rb
class Encrypter
def initialize(key)
@key = key
end
def encrypt(reader, writer)
key_index = 0
until reader.eof?
clear_char = reader.getc
encrypted_char = clear_char ^ @key[key_index]
writer.putc(encrypted_char)
key_index = (key_index + 1) % @key.size
end
end
end
# main.rb
require './renderer'
require './text_object'
require './british_text_object'
# === Modify the BritishTextObject class === #
# Extend the BritishTextObject to include the methods that the Renderer class requires
class BritishTextObjects
def color
return colour
end
def text
return string
end
def size_inches
return size_mm / 25.4
end
end
# main.rb
....
# === Another way to achieve modifying a single instace === #
def bto.color
colour
end
def bto.text
string
end
def bto.size_inches
return size_mm/25.4
end
# main.rb
...
# === Modify a Single Instance === #
#
bto = BritishTextObject.new('test', 25.4, :yellow)
class << bto
def color
colour
end
def text
string
end
def size_inches
return size_mm/25.4
end
end
class Renderer
def render(text_object)
text = text_object.text
size = text_object.size_inches
color = text_object.color
# render the text
end
end
class StringIOAdapter
def initialize(string)
@string = string
@position = 0
end
def getc
if @position >= @string.length
raise EOFError
end
ch = @string[@position]
@position += 1
return ch
end
def eof?
return @position >= @string.length
end
end
class TextObject
attr_reader :text, :size_inches, :color
def initialize(text, size_inches, color)
@text = text
@size_inches = size_inches
@color = color
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment