module Bovem::ConsoleMethods::StyleHandling::ClassMethods

Class methods for handling styles in the terminal.

Public Instance Methods

parse_style(style) click to toggle source

Parse a style and returns terminal codes.

Supported styles and colors are those in {Bovem::TERM_COLORS} and {Bovem::TERM_EFFECTS}.

You can also prefix colors with `bg_` (like `bg_red`) for background colors.

@param style [String] The style to parse. @return [String] A string with ANSI color codes.

# File lib/bovem/console.rb, line 29
def parse_style(style)
  style = style.ensure_string.strip.parameterize

  if style.present?
    Bovem::Console.replace_term_code(Bovem::TERM_EFFECTS, style, 0) ||
      Bovem::Console.replace_term_code(Bovem::TERM_COLORS, style, 30) ||
      Bovem::Console.replace_term_code(Bovem::TERM_COLORS, style.gsub(/^bg_/, ""), 40) ||
      ""
  else
    ""
  end
end
parse_styles(styles) click to toggle source

Parses a set of styles and returns terminals codes. Supported styles and colors are those in {Bovem::TERM_COLORS} and {Bovem::TERM_EFFECTS}.

You can also prefix colors with `bg_` (like `bg_red`) for background colors.

@param styles [String] The styles to parse. @return [String] A string with ANSI color codes.

# File lib/bovem/console.rb, line 48
def parse_styles(styles)
  styles.split(/\s*[\s,-]\s*/).map { |s| parse_style(s) }.join("")
end
replace_markers(message, plain = false) click to toggle source

Replaces colors markers in a string.

You can specify markers by enclosing in `{mark=}` and `{/mark}` tags.

Separate styles with spaces, dashes or commas. Nesting markers is supported.

Example:

“`ruby Bovem::Console.new.replace_markers(“{mark=bright bg_red}{mark=green}Hello world!{/mark}{/mark}”) # => “e[1me[41me[32mHello world!e[1me[41me[0m” “`

@param message [String] The message to analyze. @param plain [Boolean] If ignore (cleanify) color markers into the message. @return [String] The replaced message. @see parse_style

# File lib/bovem/console.rb, line 80
def replace_markers(message, plain = false)
  stack = []

  message.ensure_string.gsub(/((\{mark=([a-z\-_\s,]+)\})|(\{\/mark\}))/mi) do
    if $LAST_MATCH_INFO[1] == "{/mark}" # If it is a tag, pop from the latest opened.
      stack.pop
      plain || stack.blank? ? "" : Bovem::Console.parse_styles(stack.last)
    else
      add_style($LAST_MATCH_INFO[3], plain, stack)
    end
  end
end
replace_term_code(codes, code, modifier = 0) click to toggle source

Replaces a terminal code.

@param codes [Array] The valid list of codes. @param code [String] The code to lookup. @param modifier [Fixnum] The modifier to apply to the code. @return [String|nil] The terminal code or `nil` if the code was not found.

# File lib/bovem/console.rb, line 59
def replace_term_code(codes, code, modifier = 0)
  sym = code.to_sym
  codes.include?(sym) ? "\e[#{modifier + codes[sym]}m" : nil
end