class ProcSource

Constants

SOURCIFY_ERRORS

Attributes

proc[R]

Public Class Methods

new(proc = nil, &block) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 13
def initialize(proc = nil, &block)
  if proc
    fail ArgumentError, 'cannot pass both an argument and a block' if block
    fail ArgumentError, 'argument must be a Proc'                  unless proc.is_a?(Proc)
  end

  @proc = proc || block
end

Public Instance Methods

==(other) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 22
def ==(other)
  case
  when other.proc == proc
    true
  when other.arity != arity || other.lambda? != lambda?
    false
  else
    other.sexp == sexp
  end
rescue *SOURCIFY_ERRORS
  false
end
=~(other)
Alias for: match
inspect()
Alias for: to_s
match(other) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 35
def match(other)
  self == other || source_equal(other)
rescue *SOURCIFY_ERRORS
  false
end
Also aliased as: =~
raw_source() click to toggle source
# File lib/proc_extensions/proc_source.rb, line 43
def raw_source
  extract_source(:to_raw_source)
end
source() click to toggle source
# File lib/proc_extensions/proc_source.rb, line 47
def source
  extract_source(:to_source)
end
to_s() click to toggle source
# File lib/proc_extensions/proc_source.rb, line 51
def to_s
  source
rescue *SOURCIFY_ERRORS
  proc.to_s
end
Also aliased as: inspect

Protected Instance Methods

parameters() click to toggle source
# File lib/proc_extensions/proc_source.rb, line 70
def parameters
  sexp[2].sexp_body.to_a
end
sexp() click to toggle source
# File lib/proc_extensions/proc_source.rb, line 66
def sexp
  @sexp ||= proc.to_sexp
end
source_equal(other) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 74
def source_equal(other)
  other.count == count && other.lambda? == lambda? && other.sexp == sexp_with_parameters_from(other)
end

Private Instance Methods

extract_source(method) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 89
def extract_source(method)
  return '' unless proc
  proc_source = proc.public_send(method)
  lambda? ? proc_source.sub('proc ', 'lambda ') : proc_source
end
sexp_with_parameters_from(other_proc) click to toggle source
# File lib/proc_extensions/proc_source.rb, line 80
def sexp_with_parameters_from(other_proc)
  new_sexp = sexp.sub(sexp[2], other_proc.sexp[2])
  other_proc.parameters.each_with_index do |to, index|
    from = parameters[index]
    new_sexp = new_sexp.gsub(s(:lvar, from), s(:lvar, to))
  end
  new_sexp
end