Method: Inker::Color::Tools#parse_color

Defined in:
lib/inker/color/tools.rb

#parse_color(color_str) ⇒ Hash

Parse a color string an return it's RGBA components as a hash.

Examples:

Inker::Color.parse_color("#FF005544") # returns {:red=>255, :green=>0, :blue=>85, :alpha=>0.4}

Parameters:

  • color_str (String)

    color string to parse

Returns:

  • (Hash)

    a hash which contains RGBA components of parsed color

Raises:

  • (ArgumentError)


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/inker/color/tools.rb', line 256

def parse_color(color_str)
  # Normalize input string by stripping white spaces and converting
  # string to downcase
  input = color_str.to_s.strip.downcase

  # By default result is nil
  result = nil

  # Try to guess the format of color string and parse it by
  # using the apropriate algorithm
  if hex?(input)
    # Parse the string as HEX color
    result = parse_hex(input)
  elsif rgb?(input)
    # Parse the string as RGB color
    result = parse_rgb(input)
  elsif rgba?(input)
    # Parse the string as RGBA color
    result = parse_rgb(input, is_rgba: true)
  elsif hsl?(input)
    # Parse the string as HSL color
    result = parse_hsl(input)
  elsif hsla?(input)
    # Parse the string as HSLA color
    result = parse_hsl(input, is_hsla: true)
  else
    # Check if color is in "named color" format
    named_color = Inker.named_colors[input]
    if named_color
      # If a named color has been matched, use it's HEX value and
      # parse it as HEX color
      result = parse_hex(named_color)
    end
  end

  # If we didn't have any match, throw an ArgumentError error
  raise ArgumentError, "Unknown color format: #{color_str.to_s.strip.inspect}" if result.nil?

  result
end