From blog post here.
Created
January 21, 2012 23:41
-
-
Save robcthegeek/1654531 to your computer and use it in GitHub Desktop.
Ruby Open Classes - Code Examples
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 String | |
# taken from: http://regexlib.com/REDetails.aspx?regexp_id=2558 - (escaped the forward-slashes as well) | |
def is_email? | |
self =~ /^((([!#$\%&'*+\-\/=?^_`{|}~\w])|([!#$\%&'*+\-\/=?^_`{|}~\w][!#$\%&'*+\-\/=?^_`{|}~\.\w]{0,}[!#$\%&'*+\-\/=?^_`{|}~\w]))[@]\w+([-.]\w+)*\.\w+([-.]\w+)*)$/ | |
end | |
def isnt_email? | |
!is_email? | |
end | |
end | |
puts "See this is an email!" if "[email protected]".is_email? | |
puts "And so is this" if "[email protected]".is_email? | |
puts "but I'm not!" if "fail".isnt_email? |
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
# pretend this is in an OSS library.. | |
class PrinterError | |
attr_reader :code | |
def initialize(code) | |
@code = code | |
end | |
end | |
# So at this point the code is defined elsewhere, let's open it up to add our messages. | |
class PrinterError | |
def message | |
@code == 42 ? "PC LOAD ERROR" : "Unexpected error printing document" | |
end | |
end | |
puts PrinterError.new(100).message | |
puts PrinterError.new(42).message |
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
# using a completey normal string method.. | |
puts "oh hai!".upcase | |
# along comes a naughty developer | |
class String | |
def upcase | |
"#{self}\nCATS: ALL YOUR BASE ARE BELONG TO US." | |
end | |
end | |
# now what happens when we call the same code as before?? | |
puts "oh hai!".upcase |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment