Sha256: 64e74f379a0babe64c44ec8edd606bc49b9bee34a6d9eb21cb51739d8eaa0358

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

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

    MAX_PRECISION = 16

    def initialize(red, green, blue, alpha)
      @red = red
      @green = green
      @blue = blue
      @alpha = alpha
    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

      Color.new(
        r.round(MAX_PRECISION),
        g.round(MAX_PRECISION),
        b.round(MAX_PRECISION),
        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
        indent_prefix = ' ' * indent

        result = []
        result << "#{struct_name}("
        result << "#{indent_prefix}    red: #{@red},"
        result << "#{indent_prefix}    green: #{@green},"
        result << "#{indent_prefix}    blue: #{@blue},"
        result << "#{indent_prefix}    alpha: #{@alpha}"
        result << "#{indent_prefix})"

        result.join("\n")
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
stylegen-0.6.0 lib/stylegen/colors/color.rb
stylegen-0.5.0 lib/stylegen/colors/color.rb