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: Labels, Rockets

Class Method Summary collapse

Class Method Details

.for(container) ⇒ Object



1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
# File 'lib/syntax_tree/node.rb', line 1316

def self.for(container)
  labels =
    container.assocs.all? do |assoc|
      next true if assoc.is_a?(AssocSplat)

      case assoc.key
      when Label
        true
      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
        value.match?(/^[_A-Za-z]/) && !value.end_with?("=")
      when DynaSymbol
        true
      else
        false
      end
    end

  (labels ? Labels : Rockets).new
end