Method: Planter::Color#rgb

Defined in:
lib/planter/color.rb

#rgb(hex) ⇒ String

Generate escape codes for hex colors

Parameters:

  • hex (String)

    The hexadecimal color code

Returns:

  • (String)

    ANSI escape string



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/planter/color.rb', line 326

def rgb(hex)
  is_bg = /^bg?#/.match?(hex)
  hex_string = hex.sub(/^([fb]g?)?#/, '')

  if hex_string.length == 3
    parts = hex_string.match(/(?<r>.)(?<g>.)(?<b>.)/)

    t = []
    %w[r g b].each do |e|
      t << parts[e]
      t << parts[e]
    end
    hex_string = t.join('')
  end

  parts = hex_string.match(/(?<r>..)(?<g>..)(?<b>..)/)
  t = []
  %w[r g b].each do |e|
    t << parts[e].hex
  end

  "\e[#{is_bg ? '48' : '38'};2;#{t.join(';')}m"
end