Permalink
Browse files

Added the Adapter pattern related files

  • Loading branch information...
1 parent f61d0ca commit 6f3ca4a68f20954cd2b94a2485d85c51b9f75954 @adomokos committed Dec 9, 2009
Showing with 118 additions and 0 deletions.
  1. +21 −0 Adapter/encrypter.rb
  2. +27 −0 Adapter/stringio_adapter.rb
  3. +70 −0 Adapter/text_renderer_example.rb
View
@@ -0,0 +1,21 @@
+class Encrypter
+ def initialize(key)
+ @key = key
+ end
+
+ def encrypt(reader, writer)
+ key_index = 0
+ while not reader.eof?
+ clear_char = reader.getc
+ encrypter_char = clear_char ^ @key[key_index]
+ writer.putc(encrypter_char)
+ key_index = (key_index + 1) % @key.size
+ end
+ end
+end
+
+reader = File.open('message.txt')
+writer = File.open('message.encrypted', 'w')
+encrypter = Encrypter.new('my secret key')
+encrypter.encrypt(reader, writer)
+
@@ -0,0 +1,27 @@
+require 'encrypter'
+
+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
+
+encrypter = Encrypter.new('XYZZY')
+reader = StringIOAdapter.new('We attach at dawn')
+writer = File.open('out.txt', 'w')
+encrypter.encrypt(reader, writer)
+
@@ -0,0 +1,70 @@
+class Renderer
+ def rendered(text_object)
+ text = text_object.text
+ size = text_object.size_inches
+ color = text_object.color
+
+ # render the text...
+ puts 'text object rendered'
+ 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
+
+class BritishTextObject
+ attr_reader :string, :size_mm, :colour
+
+ def initialize(string, size_mm, colour)
+ @string = string
+ @size_mm = size_mm
+ @colour = colour
+ end
+end
+
+# Reopen the class and add some methods to it
+# This will effect all instances
+class BritishTextObject
+ def color
+ return colour
+ end
+
+ def text
+ return string
+ end
+
+ def size_inches
+ return size_mm / 25.4
+ end
+end
+
+# Or modify just a single instance
+bto = BritishTextObject.new('hello', 50.8, :blue)
+
+class << bto
+ def color
+ return colour
+ end
+
+ def text
+ return string
+ end
+
+ def size_inches
+ return size_mm / 25.4
+ end
+end
+
+text_object = TextObject.new('hello from TextObject', 40.73, :red)
+
+renderer = Renderer.new
+renderer.rendered bto
+renderer.rendered text_object
+

0 comments on commit 6f3ca4a

Please sign in to comment.