Class: Kolor::ColorizedString

Inherits:
Object
  • Object
show all
Includes:
Kolor, Extra
Defined in:
lib/kolor.rb

Overview

Wrapper class to enable method chaining with ANSI codes

Constant Summary

Constants included from Kolor

ANSI_REGEX, VERSION

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Extra

#color, define_all_themes, define_theme_method, get_theme, #gradient, normalize_styles, #on_color, #on_hex, #on_rgb, #rainbow, remove_theme, #rgb, theme, theme_defined?, themes, #with_hex

Methods included from Kolor

background_code, clear_code, colors, disable!, enable!, foreground_code, strip, style_code, #to_eol, #uncolorize

Constructor Details

#initialize(string, codes = []) ⇒ ColorizedString

Returns a new instance of ColorizedString.



132
133
134
135
# File 'lib/kolor.rb', line 132

def initialize(string, codes = [])
  @string = string
  @codes = codes
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Delegate string methods to the underlying string



164
165
166
167
168
169
170
171
# File 'lib/kolor.rb', line 164

def method_missing(method_name, *args, &block)
  if @string.respond_to?(method_name)
    result = @string.public_send(method_name, *args, &block)
    result.is_a?(String) ? self.class.new(result, @codes) : result
  else
    super
  end
end

Instance Attribute Details

#codesObject (readonly)

Returns the value of attribute codes.



130
131
132
# File 'lib/kolor.rb', line 130

def codes
  @codes
end

#stringObject (readonly)

Returns the value of attribute string.



130
131
132
# File 'lib/kolor.rb', line 130

def string
  @string
end

Instance Method Details

#add_code(code) ⇒ ColorizedString

Adds a new ANSI code to the chain

Parameters:

  • code (String)

    ANSI escape code to add

Returns:



157
158
159
160
161
# File 'lib/kolor.rb', line 157

def add_code(code)
  return self unless Kolor.enabled? && code

  ColorizedString.new(@string, @codes + [code])
end

#clearString

Clears all formatting and returns plain string

Returns:

  • (String)

    plain string without ANSI codes



150
151
152
# File 'lib/kolor.rb', line 150

def clear
  @string
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


173
174
175
# File 'lib/kolor.rb', line 173

def respond_to_missing?(method_name, include_private = false)
  @string.respond_to?(method_name, include_private) || super
end

#to_sString Also known as: to_str

Returns the fully colorized string

Returns:

  • (String)

    string with all ANSI codes applied



139
140
141
142
143
# File 'lib/kolor.rb', line 139

def to_s
  return @string unless Kolor.enabled?

  "#{@codes.join}#{@string}#{Kolor.clear_code}"
end