Module: Rewrite::ClassMethods

Included in:
Rewrite
Defined in:
lib/rewrite.rb

Instance Method Summary collapse

Instance Method Details

#arr_for(&proc) ⇒ Object

Convert an expression to a sexp and then the sexp to an array. Useful for tests where you want to compare results.



91
92
93
# File 'lib/rewrite.rb', line 91

def arr_for &proc
  sexp_for(&proc).to_a
end

#gensymObject

Provide a symbol that is extremely unlikely to be used elsewhere.

Rewriters use this when they need to name something. For example, Andand converts code like this:

numbers.andand.inject(&:+)

Into:

lambda { |__1234567890__|
  if __1234567890__.nil?
    nil
  else
    __1234567890__.inject(&:+)
  end
}.call(numbers)

It uses Rewrite.gensym to generate 1234567890.



75
76
77
# File 'lib/rewrite.rb', line 75

def gensym
  :"__#{Time.now.to_i}#{rand(100000)}__"
end

#recursive_s(node) ⇒ Object

Convert an object of some type to a sexp, very useful when you have a sexp expressed as a tree of arrays.



97
98
99
100
101
102
103
# File 'lib/rewrite.rb', line 97

def recursive_s(node)
  if node.is_a? Array
    s(*(node.map { |subnode| recursive_s(subnode) }))
  else
    node
  end
end

#sexp_for(&proc) ⇒ Object

Convert an expression to a sexp by taking a block and stripping\ the outer prc from it.



81
82
83
84
85
86
87
# File 'lib/rewrite.rb', line 81

def sexp_for &proc
  sexp = proc.to_sexp
  return if sexp.length != 3
  return if sexp[0] != :proc
  return unless sexp[1].nil?
  sexp[2]
end