Module: Synvert::Core::Rewriter::Helper

Included in:
Instance
Defined in:
lib/synvert/core/rewriter/helper.rb

Overview

Rewriter::Helper provides some helper methods to make it easier to write a snippet.

Instance Method Summary collapse

Instance Method Details

#add_arguments_with_parenthesis_if_necessaryString

Add arguments with parenthesis if necessary.

Examples:


add_arguments_with_parenthesis_if_necessary

if current_node doesn't have an argument, it returns ""
if current_node has argument, it returns "({{arguments}})"

Returns:

  • (String)

    return ‘({arguments})` if node.arguments present, otherwise return nothing.



35
36
37
38
39
40
41
# File 'lib/synvert/core/rewriter/helper.rb', line 35

def add_arguments_with_parenthesis_if_necessary
  if node.arguments.size > 0
    '({{arguments}})'
  else
    ''
  end
end

#add_curly_brackets_if_necessary(code) ⇒ String

Add curly brackets to code if necessary.

Examples:


add_curly_brackets_if_necessary("{{arguments}}")

Parameters:

  • code (String)

    old code

Returns:

  • (String)

    new code



51
52
53
54
55
56
57
# File 'lib/synvert/core/rewriter/helper.rb', line 51

def add_curly_brackets_if_necessary(code)
  if code.start_with?('{') && code.end_with?('}')
    code
  else
    "{ #{code} }"
  end
end

#add_receiver_if_necessary(code) ⇒ String

Add receiver to code if necessary.

Examples:


add_receiver_if_necessary("{{message}} {{arguments}}")

if current_node doesn't have a receiver, it returns "{{message}} {{arguments}}"
if current_node has a receiver, it returns "{{receiver}}.{{message}} {{arguments}}"

Parameters:

  • code (String)

    old code

Returns:

  • (String)

    new code



17
18
19
20
21
22
23
# File 'lib/synvert/core/rewriter/helper.rb', line 17

def add_receiver_if_necessary(code)
  if node.receiver
    "{{receiver}}.#{code}"
  else
    code
  end
end

#reject_keys_from_hash(hash_node, *keys) ⇒ String

Reject some keys from hash node.

Examples:


hash_node = Parser::CurrentRuby.parse("{ key1: 'value1', key2: 'value2' }")
reject_keys_from_hash(hash_node, :key1) => "key2: 'value2'"

Parameters:

  • hash_node (Parser::AST::Node)
  • keys (Array)

    keys should be rejected from the hash.

Returns:

  • (String)

    source of of the hash node after rejecting some keys.



83
84
85
# File 'lib/synvert/core/rewriter/helper.rb', line 83

def reject_keys_from_hash(hash_node, *keys)
  hash_node.children.reject { |pair_node| keys.include?(pair_node.key.to_value) }.map(&:to_source).join(', ')
end

#strip_brackets(code) ⇒ String

Remove leading and trailing brackets.

Examples:


strip_brackets("(1..100)") #=> "1..100"

Parameters:

  • code (String)

    old code

Returns:

  • (String)

    new code



67
68
69
70
71
# File 'lib/synvert/core/rewriter/helper.rb', line 67

def strip_brackets(code)
  code.sub(/^\((.*)\)$/) { Regexp.last_match(1) }.sub(/^\[(.*)\]$/) { Regexp.last_match(1) }.sub(/^{(.*)}$/) {
    Regexp.last_match(1).strip
  }
end