module Behold

Constants

DEFAULT_TIMEOUT
DOUBLE_FUZZ
EMPTY_FUZZ
FORBIDDEN
FUZZ
FUZZES
MAJOR_VERSION
MINOR_VERSION
RESULT_COUNT
TEENY_VERSION
VERSION

Public Class Methods

call(from, to) click to toggle source
# File lib/behold.rb, line 39
def call(from, to)
  black_hole do
    lazy_tries = FUZZES.map.with_index do |fuzz, index|
      match(from: from, to: to, fuzz: fuzz, arg_count: index)
    end

    best_matches(lazy_tries)
  end
end
code(from, to) click to toggle source
# File lib/behold.rb, line 33
def code(from, to)
  call(from, to).map do |meth, *args|
    "#{from.inspect}.#{meth}#{"(#{args.map(&:inspect).join ', '})" unless args.empty?}"
  end
end

Private Class Methods

arg_methods(object, args) click to toggle source
# File lib/behold.rb, line 107
def arg_methods(object, args)
  object.public_methods.select do |meth|
    next if FORBIDDEN.include? meth

    meth_arity_range = object.public_method(meth).arity_range
    next unless meth_arity_range.fetch(:keywords).min.zero?

    mandatory_args, allowable_args = meth_arity_range.fetch(:arguments).minmax

    mandatory_args <= args && allowable_args >= args
  end.lazy
end
best_matches(lazy_tries, matches = []) click to toggle source
# File lib/behold.rb, line 51
def best_matches(lazy_tries, matches = [])
  Timeout.timeout DEFAULT_TIMEOUT do
    lazy_matches(lazy_tries).each { |match| matches << match }
  end

  matches
rescue Timeout::Error
  matches
end
black_hole() { || ... } click to toggle source
# File lib/behold.rb, line 77
def black_hole
  File.open File::NULL, File::APPEND do |dev_null|
    $stdout = $stderr = dev_null

    yield
  ensure
    $stdout = STDOUT
    $stderr = STDERR
  end
end
check_method(meth, *args, from:, to:) click to toggle source
# File lib/behold.rb, line 92
def check_method(meth, *args, from:, to:)
  from.public_send(meth, *args) == to
rescue StandardError, SyntaxError
  nil
end
lazy_matches(matches) click to toggle source
# File lib/behold.rb, line 88
def lazy_matches(matches)
  matches.reduce(:+).lazy.take(RESULT_COUNT)
end
match(from:, to:, fuzz:, arg_count:) click to toggle source
# File lib/behold.rb, line 61
def match(from:, to:, fuzz:, arg_count:)
  fuzz.lazy.flat_map do |args|
    found = arg_methods(soft_dup(from), arg_count).select do |meth|
      case arg_count
      when 1
        check_method(meth, args, from: soft_dup(from), to: to)
      else
        check_method(meth, *args, from: soft_dup(from), to: to)
      end
    end
    found = found.with_object(args) if args

    found.map { |*send_this| [*send_this].flatten }
  end
end
soft_dup(from) click to toggle source
# File lib/behold.rb, line 98
def soft_dup(from)
  duped_from = from.dup
  return from unless from == from.dup

  duped_from
rescue FrozenError
  from
end