Module: Prism::HashNodeExt

Included in:
HashNode, KeywordHashNode
Defined in:
lib/prism_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


23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/prism_ext.rb', line 23

def method_missing(method_name, *args, &block)
  if method_name.to_s.end_with?('_element')
    key = method_name.to_s[0..-9]
    return elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }
  elsif method_name.to_s.end_with?('_value')
    key = method_name.to_s[0..-7]
    return elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }&.value
  elsif method_name.to_s.end_with?('_source')
    key = method_name.to_s[0..-8]
    return elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }&.value&.to_source || ''
  end

  super
end

Instance Method Details

#keysObject


14
15
16
# File 'lib/prism_ext.rb', line 14

def keys
  elements.select { |element| element.type == :assoc_node }.map(&:key)
end

#respond_to_missing?(method_name, *args) ⇒ Boolean

Returns:

  • (Boolean)

38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/prism_ext.rb', line 38

def respond_to_missing?(method_name, *args)
  if method_name.to_s.end_with?('_element')
    key = method_name.to_s[0..-9]
    return !!elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }
  elsif method_name.to_s.end_with?('_value')
    key = method_name.to_s[0..-7]
    return !!elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }
  elsif method_name.to_s.end_with?('_source')
    key = method_name.to_s[0..-8]
    return !!elements.find { |element| element.type == :assoc_node && element.key.to_value.to_s == key }
  end

  super
end

#valuesObject


18
19
20
# File 'lib/prism_ext.rb', line 18

def values
  elements.select { |element| element.type == :assoc_node }.map(&:value)
end