Module: SyntaxTree::HashNodeExt

Included in:
BareAssocHash, HashLiteral
Defined in:
lib/syntax_tree_ext.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Respond key value and source for hash node



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/syntax_tree_ext.rb', line 35

def method_missing(method_name, *args, &block)
  if method_name.to_s.end_with?('_assoc')
    key = method_name.to_s[0..-7]
    return assocs.find { |assoc| assoc_key_equal?(assoc, key) }
  elsif method_name.to_s.end_with?('_value')
    key = method_name.to_s[0..-7]
    return assocs.find { |assoc| assoc_key_equal?(assoc, key) }&.value
  elsif method_name.to_s.end_with?('_source')
    key = method_name.to_s[0..-8]
    return assocs.find { |assoc| assoc_key_equal?(assoc, key) }&.value&.to_source || ''
  end

  super
end

Instance Method Details

#keysObject



26
27
28
# File 'lib/syntax_tree_ext.rb', line 26

def keys
  assocs.map(&:key)
end

#respond_to_missing?(method_name, *args) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/syntax_tree_ext.rb', line 50

def respond_to_missing?(method_name, *args)
  if method_name.to_s.end_with?('_assoc')
    key = method_name[0..-7]
    return !!assocs.find { |assoc| assoc_key_equal?(assoc, key) }
  elsif method_name.to_s.end_with?('_value')
    key = method_name[0..-7]
    return !!assocs.find { |assoc| assoc_key_equal?(assoc, key) }
  elsif method_name.to_s.end_with?('_source')
    key = method_name.to_s[0..-8]
    return !!assocs.find { |assoc| assoc_key_equal?(assoc, key) }
  end

  super
end

#valuesObject



30
31
32
# File 'lib/syntax_tree_ext.rb', line 30

def values
  assocs.map(&:value)
end