Created
June 21, 2017 16:07
-
-
Save shivabhusal/a592b628d7f24321e56d68ae07fcfa41 to your computer and use it in GitHub Desktop.
# Some use case of OpenClass feature; Added color methods to String class
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
# Some use case of OpenClass feature | |
def red(string) | |
color_code = 31 | |
"\e[#{color_code}m#{string}\e[0m" | |
end | |
def blue(string) | |
color_code = 34 | |
"\e[#{color_code}m#{string}\e[0m" | |
end | |
def pink(string) | |
color_code = 35 | |
"\e[#{color_code}m#{string}\e[0m" | |
end | |
def log(message, type: 'info') | |
if type == 'error' | |
puts red(message) | |
elsif type == 'warning' | |
puts pink(message) | |
elsif type == 'info' | |
puts blue(message) | |
end | |
end | |
log("Something bad happened", type: 'error') | |
log("Something bad might happened", type: 'warning') | |
log("Something good just happened!") | |
# ---------------------------------------------------------------------------------------- | |
# Problem in this code is, this is not so Object oriented | |
# and its not that easy to use otherwise it could be. | |
class String | |
def red | |
color_code = 31 | |
"\e[#{color_code}m#{self}\e[0m" | |
end | |
def blue | |
color_code = 34 | |
"\e[#{color_code}m#{self}\e[0m" | |
end | |
def pink | |
color_code = 35 | |
"\e[#{color_code}m#{self}\e[0m" | |
end | |
end | |
class MyLogger | |
def log(message, type: 'info') | |
if type == 'error' | |
$stderr.puts message.red | |
elsif type == 'warning' | |
$stdout.puts message.pink | |
elsif type == 'info' | |
$stdout.puts message.blue | |
end | |
end | |
end | |
logger = MyLogger.new | |
logger.log("Something bad happened", type: 'error') | |
logger.log("Something bad might happened", type: 'warning') | |
logger.log("Something good just happened!") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment