Module: NotAPipe

Defined in:
lib/not_a_pipe.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.rewrite(code) ⇒ Object



35
36
37
38
39
40
# File 'lib/not_a_pipe.rb', line 35

def rewrite(code)
  node = Unparser.parse(code)
  node = rewrite_node(node)
  # Without predefined `_` local var, parser will consider it a method. Forcibly replace all `_()` with `_`
  Unparser.unparse(node).gsub(/\b_\(\)/, '_')
end

Instance Method Details

#pipe(name) ⇒ Object

Usage:

pipe def my_method
   value >> Some.method >> _.some_call >> [_, anything]
end

Will rewrite and reevaluate method code, replacing it with code like:

def my_method
   _ = value
   _ = Some.method(_)
   _ = _.some_call
   _ = [_, anything]
end


20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/not_a_pipe.rb', line 20

def pipe(name)
  meth = is_a?(Module) ? instance_method(name) : method(name)
  # Replacement is because method_source will read `pipe def foo; ...` from source including
  # pipe decorator.
  src = meth.source.sub(/\bpipe\s*?/, '')
  src = NotAPipe.rewrite(src)

  if is_a?(Module)
    module_eval src
  else
    instance_eval src
  end
end