Class: TermColor::RuleSet

Inherits:
Object
  • Object
show all
Defined in:
lib/term_color/rule_set.rb

Overview

TermColor style rule setc class

Author:

Constant Summary collapse

RULE_SYMBOL =

Symbol used as prefix for rule name to denote rule start

'%'
RESET_SYMBOL =

String used to denote rule close / reset

'%%'
DEFAULT_RESET_RULE =
{z: {reset: :all} }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rules) ⇒ RuleSet

Construct new rule set

Examples:

rules = RuleSet.new({
    # Green underlined text; will auto reset fg and disable underline
    # for close, since no z: is provided
    name: {fg: :green, enable: :underline},
    # Italic text; will auto generate z: that disables italic
    quote: { enable: :italic },
    # A weird rule that will make fg red inside rule,
    # and change fg to blue after rule block ends
    weird: { a: { fg: :red }, z: { fg: :blue }}
})

print rules.colorize("%nameJohn%%: '%%quoteRoses are %%weirdRed%% (blue)%%.\n")
# Result will be:
#   fg green+underline "John"
#   regular ":  "
#   italic "Roses are "
#   fg red (still italic) "Red"
#   (fg blue)(still italic) "(blue)"
#   (regular) "."

Parameters:

  • rules (Hash)

    Hash of rule names mapping to rule hashes, which can define before rules (‘a:`), after rules (`z:`) or both.

    • If neither are given, content is treated as though it was inside a ‘a:` key.

    • If ‘a:` only is given, Rule evaluate method attempts to

      auto guess `z:`, resetting any used color or style rules from `a:`
      

See Also:



47
48
49
50
51
52
# File 'lib/term_color/rule_set.rb', line 47

def initialize(rules)
    @base_rules = rules
    @base_rules[:default] = @base_rules.fetch(:default, DEFAULT_RESET_RULE)
    evaluate_rules
    build_regexs
end

Instance Attribute Details

#regexsObject (readonly)

Returns the value of attribute regexs.



17
18
19
# File 'lib/term_color/rule_set.rb', line 17

def regexs
  @regexs
end

#rulesObject (readonly)

Returns the value of attribute rules.



17
18
19
# File 'lib/term_color/rule_set.rb', line 17

def rules
  @rules
end

Instance Method Details

#apply(text) ⇒ String

Apply styling to string using rule set

Parameters:

  • text (String)

    Text to parse for stylization

Returns:

  • (String)

    Text with ANSI style codes injected



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/term_color/rule_set.rb', line 58

def apply(text)
    raw = process_text(text)
    last_rule = nil
    str = ''
    raw.each do |r|
        if r.is_a?(Symbol)
            # if (r == :close_rule && !last_rule.nil?)
            #     str.concat(Rule.codes(@rules[last_rule][:z]))
            #     last_rule = nil
            # elsif  r == :default
            #     str.concat(Rule.codes(@rules[r][:z]))
            #     last_rule = nil
            # else
            #     last_rule = r
            #     str.concat(Rule.codes(@rules[r][:a]))
            # end
            if (r == :default) && !last_rule.nil?
                str.concat(@rules[last_rule].codes(Rule::Parts[:after]))
                last_rule = nil
            elsif  r == :default
                str.concat(@rules[r].codes(Rule::Parts[:after]))
                last_rule = nil
            else
                last_rule = r
                str.concat(@rules[r].codes(Rule::Parts[:inside]))
            end
        else
            str.concat(r)
        end
    end
    str
end

Wraps STDOUT print method, passing output of ‘apply` to `print`

Parameters:

  • args (Array)

    Print arguments, including TermColor style tags

  • opts (Hash)

    Optional params

Options Hash (**opts):

  • :out (IO)

    Optional override for IO class to call ‘print` on (default `$stdout`)



97
98
99
100
101
# File 'lib/term_color/rule_set.rb', line 97

def print(*args,**opts)
    stdout = opts.fetch(:out, $stdout)
    t = args.map{|a|apply(a)}
    stdout.print *t
end

#printf(format_string, *args, **opts) ⇒ Object

Wraps STDOUT printf method, passing output of ‘apply` to `print` Doesn’t actually use ‘printf`, instead passes result of `format_string % args` to `print`.

Parameters:

  • format_string (String)

    printf format string, including TermColor style tags

  • args (Array)

    printf values to use with format string

  • opts (Hash)

    Optional params

Options Hash (**opts):

  • :out (IO)

    Optional override for IO class to call ‘print` on (default `$stdout`)



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/term_color/rule_set.rb', line 113

def printf(format_string,*args,**opts)
    stdout = opts.fetch(:out, $stdout)

    # Sanitize rule symbols
    sanitized = format_string.dup
    @rules.keys.each { |k| sanitized.gsub!("#{RULE_SYMBOL}#{k.to_s}","#{255.chr}#{k.to_s}") }
    sanitized.gsub!(RESET_SYMBOL, 255.chr*2)
    
    t = sanitized % args
    # Reinstate rule symbols
    @rules.keys.each { |k| t.gsub!("#{255.chr}#{k.to_s}","#{RULE_SYMBOL}#{k.to_s}") }
    t.gsub!(255.chr*2,RESET_SYMBOL)
    
    stdout.print apply(t)
end