Created
February 24, 2009 03:34
-
-
Save jwreagor/69389 to your computer and use it in GitHub Desktop.
How to properly extend String and abstract in new functionality using the Proxy Pattern without overriding native Ruby primitives.
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
#!/usr/bin/env ruby | |
# | |
# How to properly extend String and abstract in new functionality using the Proxy Pattern | |
# without overriding native Ruby primitives. | |
# | |
# [og](http://www.fngtps.com/2006/09/the-proxy-pattern-in-ruby) | |
# | |
require 'rubygems' | |
require 'bacon' | |
module Formatting | |
class Formatter < String | |
alias :to_str :to_s | |
def initialize(str) | |
super | |
@str = str | |
end | |
def to_str | |
@str | |
end | |
def format(str=nil) | |
Formatter.new(str || self) | |
end | |
end | |
def self.register(mod) | |
Formatter.send :include, mod | |
end | |
end | |
module UpTheCase | |
def upthecase | |
format @str.upcase! | |
end | |
end | |
module UnNewLine | |
def unnewlined | |
format @str.gsub!(/\r\n/, '') | |
end | |
end | |
describe Formatting::Formatter do | |
before do | |
@string = Formatting::Formatter.new("test out \r\n") | |
end | |
it "should register UpTheCase's instance methods" do | |
Formatting.register UpTheCase | |
Formatting::Formatter.instance_methods.should.include(*UpTheCase.instance_methods) | |
end | |
it "should register UnNewLine's instance methods" do | |
Formatting.register UnNewLine | |
Formatting::Formatter.instance_methods.should.include(*UnNewLine.instance_methods) | |
end | |
it "should up the case" do | |
Formatting.register UpTheCase | |
@string.format.upthecase.should == "TEST OUT \r\n" | |
end | |
it "should remove new lines" do | |
Formatting.register UnNewLine | |
@string.format.unnewlined.should == "test out " | |
end | |
end | |
Bacon.summary_on_exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment