Sha256: 2490b9a7fcbb10093c51841e11eaa81c881d737ed0bafb0a6cd19c7e64368e33

Contents?: true

Size: 1.39 KB

Versions: 4

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

module Doing
  ##
  ## Array helpers
  ##
  class ::Array
    ##
    ## Convert an @tags to plain strings
    ##
    ## @return     [Array] array of strings
    ##
    def tags_to_array
      map(&:remove_at)
    end

    # Convert strings to @tags
    #
    # @return     [Array] Array of @tags
    #
    # @example
    #   ['one', '@two', 'three'].to_tags
    #   # => ['@one', '@two', '@three']
    def to_tags
      map(&:add_at)
    end

    def to_tags!
      replace to_tags
    end

    ##
    ## Hightlight @tags in string for console output
    ##
    ## @param      color  [String] the color to highlight
    ##                    with
    ##
    ## @return     [String] string with @tags highlighted
    ##
    def highlight_tags(color = 'cyan')
      tag_color = Doing::Color.send(color)
      to_tags.map { |t| "#{tag_color}#{t}" }
    end

    ##
    ## Tag array for logging
    ##
    ## @return     [String] Highlighted tag array joined with comma
    ##
    def log_tags
      highlight_tags.join(', ')
    end

    ##
    ## Convert array to nested hash, setting last key to value
    ##
    ## @param      value  The value to set
    ##
    def nested_hash(value)
      raise StandardError, 'Value can not be nil' if value.nil?

      hsh = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
      hsh.dig(*self[0..-2])[self.fetch(-1)] = value
      hsh
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
doing-2.1.26 lib/doing/array.rb
doing-2.1.25 lib/doing/array.rb
doing-2.1.24 lib/doing/array.rb
doing-2.1.23 lib/doing/array.rb