Sha256: 2ad5e72bc5ae299c0dd253a5d5599fbae1864c21e3ffc8216f12f80aa285f378

Contents?: true

Size: 1.3 KB

Versions: 3

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module Dato
  module Local
    module FieldType
      class Color
        attr_reader :red, :green, :blue

        def self.parse(value, _repo)
          value && new(
            value[:red],
            value[:green],
            value[:blue],
            value[:alpha],
          )
        end

        def initialize(red, green, blue, alpha)
          @red = red
          @green = green
          @blue = blue
          @alpha = alpha
        end

        def rgb
          if @alpha == 255
            "rgb(#{red}, #{green}, #{blue})"
          else
            "rgba(#{red}, #{green}, #{blue}, #{alpha})"
          end
        end

        def alpha
          @alpha / 255.0
        end

        def hex
          r = red.to_s(16)
          g = green.to_s(16)
          b = blue.to_s(16)
          a = (alpha * 255).to_i.to_s(16)

          r = "0#{r}" if r.length == 1
          g = "0#{g}" if g.length == 1
          b = "0#{b}" if b.length == 1
          a = "0#{a}" if a.length == 1

          hex = "##{r}#{g}#{b}"

          hex += a if a != "ff"

          hex
        end

        def to_hash(*_args)
          {
            red: red,
            green: green,
            blue: blue,
            rgb: rgb,
            hex: hex,
          }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dato-0.8.3 lib/dato/local/field_type/color.rb
dato-0.8.2 lib/dato/local/field_type/color.rb
dato-0.8.1 lib/dato/local/field_type/color.rb