Method: Sourcify::Proc::Stubs#to_source

Defined in:
lib/sourcify/proc.rb

#to_source(opts = {}, &body_matcher) ⇒ Object

Returns the code representation of this proc. Unlike Proc#to_raw_source, the returned code retains only the functional aspects, fluff like comments are stripped off.

lambda do |i|
  i+1 # (blah)
end.to_source
# >> "proc {|i| i+1 }"

The following options are supported:

  • :strip_enclosure when set to true, strips the enclosing “proc { … }” to get just the meat within.

    lambda {|i| i+1 }.to_source(:strip_enclosure => true)
    # >> "i+2"
    

    (this option is effective regardless of presence of ParseTree)

  • :attached_to is useful to avoid the nasty Sourcify::MultipleMatchingProcsPerLineError (as a result of ambiguities when doing static code analysis), it declares the condition that must be met prior grabbing the code block:

    x = lambda { proc { :blah } }
    
    x.to_source
    # >> Sourcify::MultipleMatchingProcsPerLineError
    
    x.to_source(:attached_to => :lambda)
    # >> "proc { proc { :blah } }"
    

    Sometimes more control is needed:

    # We want to ignore everything associated with ignore
    def ignore(&block); block; end
    x = lambda { ignore { :blah } }
    
    x.to_source
    # >> Sourcify::MultipleMatchingProcsPerLineError
    
    x.to_source(:attached_to => /^(.*\W|)(lambda|proc)\W/)
    # >> "proc { ignore { :blah } }"
    

    (this option is effective ONLY when ParseTree is not available)

  • :ignore_nested is useful when only the outermost proc matters and we want to ignore all other nested proc(s):

    x = lambda { lambda { :blah } }
    
    x.to_source
    # >> Sourcify::MultipleMatchingProcsPerLineError
    
    x.to_source(:ignore_nested => true)
    # >> "proc { lambda { :blah } }"
    

    However, since code scanning stops at the outermost proc, beware of the following:

    x = lambda {|_| lambda { lambda { :blah } } }.call(nil)
    
    x.to_source
    # >> "proc { lambda { :blah } }"
    
    x.to_source(:ignore_nested => true)
    # >> Sourcify::NoMatchingProcError
    

    (this option is effective ONLY when ParseTree is not available)

When in static code analysis (non-ParseTree) mode, it is even possible to specify how the proc body should look like by passing in a code block:

x, y = lambda { def secret; 1; end }, lambda { :blah }

x.to_source
# >> Sourcify::MultipleMatchingProcsPerLineError

x.to_source{|body| body =~ /^(.*\W|)def\W/ }
# >> "proc { def secret; 1; end }"


142
143
144
# File 'lib/sourcify/proc.rb', line 142

def to_source(opts={}, &body_matcher)
  # NOTE: this is a stub for the actual one in Methods::ToSource
end