Sha256: fa59609e40791cf40e634cd81691e4cfb2d0d9c24e004ca6bfd80bd5206fe21c

Contents?: true

Size: 1.22 KB

Versions: 4

Compression:

Stored size: 1.22 KB

Contents

# frozen_string_literal: true

require "json"

module Primer
  module ViewComponents
    # A module for constants that are used in the view components.
    class Constants
      CONSTANTS = JSON.parse(
        File.read(
          File.join(File.dirname(__FILE__), "../../../static/constants.json")
        )
      ).freeze

      class << self
        def get(component:, constant:, invert: true, symbolize: false)
          values = CONSTANTS.dig(component, constant)

          case values
          when Hash
            format_hash(values, invert, symbolize)
          when Array
            format_array(values, symbolize)
          else
            values
          end
        end

        private

        def format_hash(values, invert, symbolize)
          val = values.invert if invert
          # remove defaults
          val = val.except("", nil)

          return val.transform_values { |v| symbolize_value(v) } if symbolize

          val
        end

        def format_array(values, symbolize)
          val = values.select(&:present?)

          return val.map { |v| symbolize_value(v) } if symbolize

          val
        end

        def symbolize_value(value)
          ":#{value}"
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
primer_view_components-0.0.52 lib/primer/view_components/constants.rb
primer_view_components-0.0.51 lib/primer/view_components/constants.rb
primer_view_components-0.0.50 lib/primer/view_components/constants.rb
primer_view_components-0.0.49 lib/primer/view_components/constants.rb