Sha256: 18dde480450af26c3b83555e679f409746a6720cb1507af621c254640fad7416

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

module Stylegen
  class Color
    attr_reader :red, :green, :blue, :alpha

    def initialize(r, g, b, a)
      @red, @green, @blue, @alpha = r, g, b, a
    end

    def self.from_hex(hex, alpha = nil)
      if (match = hex.downcase.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/))
        r = Integer(match.captures[0], 16) / 255.0
        g = Integer(match.captures[1], 16) / 255.0
        b = Integer(match.captures[2], 16) / 255.0
      elsif (match = hex.downcase.match(/^#?([a-f\d])([a-f\d])([a-f\d])$/))
        r = Integer(match.captures[0] * 2, 16) / 255.0
        g = Integer(match.captures[1] * 2, 16) / 255.0
        b = Integer(match.captures[2] * 2, 16) / 255.0
      else
        raise ArgumentError, "Invalid color syntax: #{hex}"
      end

      max_digits = 2

      Color.new(r.round(max_digits), g.round(max_digits), b.round(max_digits), alpha || 1.0)
    end

    def grayscale?
      @red == @green && @green == @blue
    end

    def to_s(struct_name, _indent = 0)
      if grayscale?
        "#{struct_name}(white: #{@red}, alpha: #{@alpha})"
      else
        "#{struct_name}(red: #{@red}, green: #{@green}, blue: #{@blue}, alpha: #{@alpha})"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
stylegen-0.3.0 lib/stylegen/colors/color.rb
stylegen-0.2.0 lib/stylegen/colors/color.rb
stylegen-0.1.0 lib/stylegen/colors/color.rb