Sha256: 888afa35a13680ccd17907fd0fae65575c21bb433fc28fbb0ff712749b1f6722

Contents?: true

Size: 1.6 KB

Versions: 4

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

module Licensee
  class LicenseField < Struct.new(:name, :description)
    class << self
      # Return a single license field
      #
      # key - string representing the field's text
      #
      # Returns a LicenseField
      def find(key)
        @all.find { |f| f.key == key }
      end

      # Returns an array of strings representing all field keys
      def keys
        @keys ||= LicenseField.all.map(&:key)
      end

      # Returns an array of all known LicenseFields
      def all
        @all ||= begin
          path   = '../../vendor/choosealicense.com/_data/fields.yml'
          path   = File.expand_path path, __dir__
          fields = YAML.safe_load_file(path)
          fields.map { |field| LicenseField.from_hash(field) }
        end
      end

      # Builds a LicenseField from a hash of properties
      def from_hash(hash)
        ordered_array = hash.values_at(*members.map(&:to_s))
        new(*ordered_array)
      end

      # Given an array of keys, returns an array of coresponding LicenseFields
      def from_array(array)
        array.map { |key| LicenseField.find(key) }
      end

      # Given a license body, returns an array of included LicneseFields
      def from_content(content)
        return [] unless content

        LicenseField.from_array content.scan(FIELD_REGEX).flatten
      end
    end

    alias key name
    FIELD_REGEX = /\[(#{Regexp.union(LicenseField.keys)})\]/

    # The human-readable field name
    def label
      key.sub('fullname', 'full name').capitalize
    end
    alias to_s label

    def raw_text
      "[#{key}]"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
licensee-9.18.0 lib/licensee/license_field.rb
licensee-9.17.1 lib/licensee/license_field.rb
licensee-9.17.0 lib/licensee/license_field.rb
licensee-9.16.1 lib/licensee/license_field.rb