Class: Doing::TemplateString
- Includes:
- Color
- Defined in:
- lib/doing/template_string.rb
Overview
Template string formatting
Constant Summary
Constants included from Color
Color::ATTRIBUTES, Color::ATTRIBUTE_NAMES, Color::ESCAPE_REGEX
Instance Attribute Summary collapse
-
#original ⇒ Object
readonly
Returns the value of attribute original.
Instance Method Summary collapse
-
#apply_colors(color_array) ⇒ Object
Apply a color array to a string.
-
#colored ⇒ String
Return string with %colors replaced with escape codes.
-
#colors? ⇒ Boolean
Test if string contains any valid %colors.
- #fill(placeholder, value, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ Object
-
#initialize(string, placeholders: {}, force_color: false, disable_color: false, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ TemplateString
constructor
A new instance of TemplateString.
-
#parse_colors ⇒ Hash
Parse a template string for %colors and return a hash of colors and string locations.
- #parsed_colors ⇒ Object
-
#raw ⇒ String
Remove all valid %colors from string.
- #reparse ⇒ Object
Methods included from Color
attributes, coloring?, #rgb, #support?, template, uncolor, #uncolor
Methods inherited from String
#good?, #last_color_code, #normalize_color, #sanitize, #uncolor, #utf8, #valid_id?, #validate_color
Methods included from Completion::StringUtils
#ltrunc, #ltrunc!, #short_desc
Methods included from ChronifyString
#chronify, #chronify_qty, #expand_date_tags, #is_range?, #split_date_range, #time_string, #to_seconds
Methods included from StringURL
#clean_unlinked_urls, #link_urls, #link_urls!, #remove_self_links, #replace_qualified_urls
Methods included from StringTruncate
#trunc, #trunc!, #truncend, #truncend!, #truncmiddle, #truncmiddle!
Methods included from StringTransform
#cap_first, #compress, #compress!, #set_type, #simple_wrap, #titlecase, #to_p, #wrap
Methods included from StringTags
#add_at, #add_tags, #add_tags!, #dedup_tags, #dedup_tags!, #remove_at, #split_tags, #tag, #tag!, #to_tags
Methods included from StringQuery
#ignore?, #ignore_case, #rx?, #to_bool, #to_phrase_query, #to_query, #to_rx, #truthy?, #wildcard_to_rx
Methods included from StringHighlight
#highlight_search, #highlight_search!, #highlight_tags, #highlight_tags!, #last_color, #uncolor, #uncolor!
Methods included from StringNormalize
#normalize_age, #normalize_age!, #normalize_bool, #normalize_bool!, #normalize_case, #normalize_case!, #normalize_change_type, #normalize_list_style, #normalize_matching, #normalize_matching!, #normalize_order, #normalize_order!, #normalize_tag_sort, #normalize_tag_sort!, #normalize_trigger, #normalize_trigger!
Constructor Details
#initialize(string, placeholders: {}, force_color: false, disable_color: false, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ TemplateString
Returns a new instance of TemplateString.
11 12 13 14 15 16 17 18 19 |
# File 'lib/doing/template_string.rb', line 11 def initialize(string, placeholders: {}, force_color: false, disable_color: false, wrap_width: 0, color: '', tags_color: '', reset: '') Color.coloring = true if force_color Color.coloring = false if disable_color @colors = nil @original = string super(Doing::Color.coloring? ? Color.reset + string : string) placeholders.each { |k, v| fill(k, v, wrap_width: wrap_width, color: color, tags_color: ) } end |
Instance Attribute Details
#original ⇒ Object (readonly)
Returns the value of attribute original.
8 9 10 |
# File 'lib/doing/template_string.rb', line 8 def original @original end |
Instance Method Details
#apply_colors(color_array) ⇒ Object
Apply a color array to a string
89 90 91 92 93 94 95 96 |
# File 'lib/doing/template_string.rb', line 89 def apply_colors(color_array) str = dup color_array.reverse.each do |color| c = color[:color].empty? ? Color.send(color[:name]) : color[:color] str.insert(color[:index], c) end str end |
#colored ⇒ String
Return string with %colors replaced with escape codes
42 43 44 45 |
# File 'lib/doing/template_string.rb', line 42 def colored reparse parsed_colors[:string].apply_colors(parsed_colors[:colors]) end |
#colors? ⇒ Boolean
Test if string contains any valid %colors
26 27 28 29 30 31 |
# File 'lib/doing/template_string.rb', line 26 def colors? scan(/%([a-z]+)/).each do return true if Regexp.last_match(1).validate_color end false end |
#fill(placeholder, value, wrap_width: 0, color: '', tags_color: '', reset: '') ⇒ Object
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/doing/template_string.rb', line 98 def fill(placeholder, value, wrap_width: 0, color: '', tags_color: '', reset: '') reparse rx = /(?mi)(?<!\\)%(?<width>-?\d+)?(?:\^(?<mchar>.))?(?:(?<ichar>[ _t]|[^a-z0-9])(?<icount>\d+))?(?<prefix>.[ _t]?)?#{placeholder.sub( /^%/, '' )}(?<after>.*?)$/ ph = raw.match(rx) return unless ph placeholder_offset = ph.begin(0) last_colors = parsed_colors[:colors].select { |v| v[:index] <= placeholder_offset + 4 } last_color = last_colors.map { |v| v[:color] }.pop(3).join('') sub!(rx) do m = Regexp.last_match after = m['after'] if !value.good? after else pad = m['width'].to_i mark = m['mchar'] || '' if placeholder == 'shortdate' && m['width'].nil? fmt_string = Doing.setting('shortdate_format.older', '%m/%d/%y %_I:%M%P', exact: true) pad = Date.today.strftime(fmt_string).length end indent = nil if m['ichar'] char = m['ichar'] =~ /t/ ? "\t" : ' ' indent = char * m['icount'].to_i end indent ||= placeholder =~ /^title/ ? '' : "\t" prefix = m['prefix'] if placeholder =~ /^tags/ prefix ||= '' value = value.map { |t| "#{prefix}#{t.sub(/^#{prefix}?/, '')}" }.join(' ') prefix = '' end if placeholder =~ /^title/ color = last_color + color if wrap_width.positive? || pad.positive? width = pad.positive? ? pad : wrap_width out = value.gsub(/%/, '\%').strip.wrap(width, pad: pad, indent: indent, offset: placeholder_offset, prefix: prefix, color: color, after: after, reset: reset, pad_first: false) else out = format("%s%s%#{pad}s%s", prefix, color, value.gsub(/%/, '\%').sub(/\s*$/, ''), after) end out.(, last_color: color) if && !.empty? out elsif placeholder =~ /^note/ if wrap_width.positive? || pad.positive? width = pad.positive? ? pad : wrap_width outstring = value.map do |l| if l.empty? ' ' else line = l.gsub(/%/, '\%').strip.wrap(width, pad: pad, indent: indent, offset: 0, prefix: prefix, color: last_color, after: after, reset: reset, pad_first: true) line.(, last_color: last_color) unless ! || !.good? "#{line} " end end.join("\n") "\n#{last_color}#{mark}#{outstring} " else out = format("\n%s%s%s%#{pad}s%s", indent, prefix, last_color, value.join("\n#{indent}#{prefix}").gsub(/%/, '\%').sub(/\s*$/, ''), after) out.(, last_color: last_color) if && !.empty? out end else format("%s%#{pad}s%s", prefix, value.gsub(/%/, '\%').sub(/\s*$/, ''), after) end end end @parsed_colors = parse_colors end |
#parse_colors ⇒ Hash
Parse a template string for %colors and return a hash of colors and string locations
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/doing/template_string.rb', line 65 def parse_colors working = dup color_array = [] scan(/(?<!\\)(%((?:[fb]g?)?#[a-fA-F0-9]{6}|[a-z]+))/).each do |color| valid_color = color[1].validate_color next unless valid_color idx = working.match(/(?<!\\)%#{valid_color}/).begin(0) color = Color.attributes.include?(valid_color.to_sym) ? Color.send(valid_color) : Color.rgb(valid_color) color_array.push({ name: valid_color, color: color, index: idx }) working.sub!(/(?<!\\)%#{valid_color}/, '') end { string: working, colors: color_array } end |
#parsed_colors ⇒ Object
56 57 58 |
# File 'lib/doing/template_string.rb', line 56 def parsed_colors @parsed_colors ||= parse_colors end |
#raw ⇒ String
Remove all valid %colors from string
52 53 54 |
# File 'lib/doing/template_string.rb', line 52 def raw parsed_colors[:string].uncolor end |
#reparse ⇒ Object
33 34 35 |
# File 'lib/doing/template_string.rb', line 33 def reparse @parsed_colors = nil end |