diff options
Diffstat (limited to 'lib/highline/string_extensions.rb')
-rw-r--r-- | lib/highline/string_extensions.rb | 44 |
1 files changed, 30 insertions, 14 deletions
diff --git a/lib/highline/string_extensions.rb b/lib/highline/string_extensions.rb index d2f2de4..f6c4c6b 100644 --- a/lib/highline/string_extensions.rb +++ b/lib/highline/string_extensions.rb @@ -1,16 +1,18 @@ # coding: utf-8 -class HighLine +class HighLine #:nodoc: # Returns a HighLine::String from any given String. # @param s [String] # @return [HighLine::String] from the given string. - def self.String(s) + def self.String(s) # rubocop:disable Naming/MethodName HighLine::String.new(s) end # HighLine extensions for String class. # Included by HighLine::String. module StringExtensions + STYLE_METHOD_NAME_PATTERN = /^(on_)?rgb_([0-9a-fA-F]{6})$/ + # Included hook. Actions to take when being included. # @param base [Class, Module] base class def self.included(base) @@ -35,7 +37,7 @@ class HighLine undef :on if method_defined? :on def on(arg) - color(('on_' + arg.to_s).to_sym) + color(("on_" + arg.to_s).to_sym) end undef :uncolor if method_defined? :uncolor @@ -57,19 +59,33 @@ class HighLine # @todo Chain existing method_missing? undef :method_missing if method_defined? :method_missing - def method_missing(method, *args, &blk) - if method.to_s =~ /^(on_)?rgb_([0-9a-fA-F]{6})$/ + def method_missing(method, *_args) + if method.to_s =~ STYLE_METHOD_NAME_PATTERN color(method) else - raise NoMethodError, "undefined method `#{method}' for #<#{self.class}:#{'%#x'%self.object_id}>" + super end end + undef :respond_to_missing if method_defined? :respond_to_missing + def respond_to_missing?(method_name, include_private = false) + method_name.to_s =~ STYLE_METHOD_NAME_PATTERN || super + end + private def setup_color_code(*colors) - color_code = colors.map{|color| color.is_a?(Numeric) ? '%02x'%color : color.to_s}.join - raise "Bad RGB color #{colors.inspect}" unless color_code =~ /^[a-fA-F0-9]{6}/ + color_code = colors.map do |color| + if color.is_a?(Numeric) + format("%02x", color) + else + color.to_s + end + end.join + + raise "Bad RGB color #{colors.inspect}" unless + color_code =~ /^[a-fA-F0-9]{6}/ + color_code end end @@ -80,28 +96,28 @@ class HighLine def self.define_builtin_style_methods(base) HighLine::COLORS.each do |color| color = color.downcase - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :#{color} if method_defined? :#{color} def #{color} color(:#{color}) end - END + METHOD_DEFINITION - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :on_#{color} if method_defined? :on_#{color} def on_#{color} on(:#{color}) end - END + METHOD_DEFINITION HighLine::STYLES.each do |style| style = style.downcase - base.class_eval <<-END + base.class_eval <<-METHOD_DEFINITION undef :#{style} if method_defined? :#{style} def #{style} color(:#{style}) end - END + METHOD_DEFINITION end end end |