Class: RubyRich::RichText

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_rich/text.rb

Constant Summary collapse

ANSI_CODES =

ANSI 转义码常量

{
  reset: "\e[0m",
  bold: "\e[1m",
  italic: "\e[3m",
  underline: "\e[4m",
  blink: "\e[5m",
  color: {
    black: "\e[30m",
    red: "\e[31m",
    green: "\e[32m",
    yellow: "\e[33m",
    blue: "\e[34m",
    magenta: "\e[35m",
    cyan: "\e[36m",
    white: "\e[37m"
  },
  background: {
    black: "\e[40m",
    red: "\e[41m",
    green: "\e[42m",
    yellow: "\e[43m",
    blue: "\e[44m",
    magenta: "\e[45m",
    cyan: "\e[46m",
    white: "\e[47m"
  }
}
@@theme =

默认主题

{
  error: { color: :red, bold: true },
  success: { color: :green, bold: true },
  info: { color: :cyan },
  warning: { color: :yellow, bold: true }
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, style: nil) ⇒ RichText

Returns a new instance of RichText.



44
45
46
47
48
# File 'lib/ruby_rich/text.rb', line 44

def initialize(text, style: nil)
  @text = text
  @styles = []
  apply_theme(style) if style
end

Class Method Details

.set_theme(new_theme) ⇒ Object



40
41
42
# File 'lib/ruby_rich/text.rb', line 40

def self.set_theme(new_theme)
  @@theme.merge!(new_theme)
end

Instance Method Details

#renderObject



60
61
62
# File 'lib/ruby_rich/text.rb', line 60

def render
  "#{@styles.join}#{@text}#{ANSI_CODES[:reset]}"
end

#style(color: nil, background: nil, bold: false, italic: false, underline: false, blink: false) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/ruby_rich/text.rb', line 50

def style(color: nil, background: nil, bold: false, italic: false, underline: false, blink: false)
  @styles << ANSI_CODES[:color][color] if color
  @styles << ANSI_CODES[:background][background] if background
  @styles << ANSI_CODES[:bold] if bold
  @styles << ANSI_CODES[:italic] if italic
  @styles << ANSI_CODES[:underline] if underline
  @styles << ANSI_CODES[:blink] if blink
  self
end