Module: SyntaxTree::HashKeyFormatter

Defined in:
lib/syntax_tree/node.rb

Overview

This module is responsible for formatting the assocs contained within a hash or bare hash. It first determines if every key in the hash can use labels. If it can, it uses labels. Otherwise it uses hash rockets.

Defined Under Namespace

Classes: Identity, Labels, Rockets

Class Method Summary collapse

Class Method Details

.for(container) ⇒ Object



1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
# File 'lib/syntax_tree/node.rb', line 1787

def for(container)
  (assocs = container.assocs).each_with_index do |assoc, index|
    if assoc.is_a?(AssocSplat)
      # Splat nodes do not impact the formatting choice.
    elsif assoc.value.nil?
      # If the value is nil, then it has been omitted. In this case we
      # have to match the existing formatting because standardizing would
      # potentially break the code. For example:
      #
      #     { first:, "second" => "value" }
      #
      return Identity.new
    else
      # Otherwise, we need to check the type of the key. If it's a label
      # or dynamic symbol, we can use labels. If it's a symbol literal
      # then it needs to match a certain pattern to be used as a label. If
      # it's anything else, then we need to use hash rockets.
      case assoc.key
      when Label, DynaSymbol
        # Here labels can be used.
      when SymbolLiteral
        # When attempting to convert a hash rocket into a hash label,
        # you need to take care because only certain patterns are
        # allowed. Ruby source says that they have to match keyword
        # arguments to methods, but don't specify what that is. After
        # some experimentation, it looks like it's:
        value = assoc.key.value.value

        if !value.match?(/^[_A-Za-z]/) || value.end_with?("=")
          if omitted_value?(assocs[(index + 1)..])
            return Identity.new
          else
            return Rockets.new
          end
        end
      else
        if omitted_value?(assocs[(index + 1)..])
          return Identity.new
        else
          return Rockets.new
        end
      end
    end
  end

  Labels.new
end