Reputation: 116
I don't understand why I can't call the method colorize
from color.rb.
I wrote include color
inside the class, but when I try to execute the script I get this error in wget
:
undefined method `colorize' for #<String:0x00000001152d30>
This is the code:
$LOAD_PATH << './lib'
require 'color'
class Download
include color
def wget(arr)
FileUtils.cd('/mnt/list')
site = "xxxxx"
arr.each do |f|
wget = system("wget #{site}#{f}")
logger.info("wget: #{f}".colorize("blue"))
end
end
end
The file color.rb with the method colorize
module Color
def colorize(color, options = {})
background = options[:background] || options[:bg] || false
style = options[:style]
offsets = ["gray","red", "green", "yellow", "blue", "magenta", "cyan","white"]
styles = ["normal","bold","dark","italic","underline","xx","xx","underline","xx","strikethrough"]
start = background ? 40 : 30
color_code = start + (offsets.index(color) || 8)
style_code = styles.index(style) || 0
"\e[#{style_code};#{color_code}m#{self}\e[0m"
end
end
Upvotes: 0
Views: 4809
Reputation: 121000
As soon as you want to call colorize
method on String
s instance, you should monkeypatch the String
class:
class String
include Color
end
include color
string in your Download
class is senseless.
The snippet might be put anywhere in your code, e. g. right after the Color
module definition. Since you have String
class monkeypatched as shown above, you yield an ability to call colorize
on string instances. The summing up:
module Color
def colorize(color, options = {})
....
end
end
class String
include Color
end
puts 'a'.colorize(...) # ⇒ works
Upvotes: 2