Module: Bovem::ConsoleMethods::StyleHandling::ClassMethods
- Defined in:
- lib/bovem/console.rb
Overview
Class methods for handling styles in the terminal.
Instance Method Summary (collapse)
-
- (String) parse_style(style)
Parse a style and returns terminal codes.
-
- (String) parse_styles(styles)
Parses a set of styles and returns terminals codes.
-
- (String) replace_markers(message, plain = false)
Replaces colors markers in a string.
-
- (String|nil) replace_term_code(codes, code, modifier = 0)
Replaces a terminal code.
Instance Method Details
- (String) parse_style(style)
Parse a style and returns terminal codes.
Supported styles and colors are those in TERM_COLORS and TERM_EFFECTS. You can also prefix colors with bg_
(like bg_red
) for background colors.
28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/bovem/console.rb', line 28 def parse_style(style) style = style.ensure_string.strip.parameterize if style.present? then ::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 |
- (String) parse_styles(styles)
Parses a set of styles and returns terminals codes.
Supported styles and colors are those in TERM_COLORS and TERM_EFFECTS. You can also prefix colors with bg_
(like bg_red
) for background colors.
46 47 48 |
# File 'lib/bovem/console.rb', line 46 def parse_styles(styles) styles.split(/\s*[\s,-]\s*/).collect { |s| parse_style(s) }.join("") end |
- (String) replace_markers(message, plain = false)
Replaces colors markers in a string.
You can specify markers by enclosing in {mark=[style]}
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[1m\e[41m\e[32mHello world!\e[1m\e[41m\e[0m"
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/bovem/console.rb', line 77 def replace_markers(, plain = false) stack = [] .ensure_string.gsub(/((\{mark=([a-z\-_\s,]+)\})|(\{\/mark\}))/mi) do if $1 == "{/mark}" then # If it is a tag, pop from the latest opened. stack.pop plain || stack.blank? ? "" : ::Bovem::Console.parse_styles(stack.last) else styles = $3.ensure_string replacement = plain ? "" : ::Bovem::Console.parse_styles(styles) if replacement.length > 0 then stack << "reset" if stack.blank? stack << styles end replacement end end end |
- (String|nil) replace_term_code(codes, code, modifier = 0)
Replaces a terminal code.
57 58 59 60 |
# File 'lib/bovem/console.rb', line 57 def replace_term_code(codes, code, modifier = 0) sym = code.to_sym codes.include?(sym) ? "\e[#{modifier + codes[sym]}m" : nil end |