Sha256: 7329915b406f9b667104e642e1797cb386dcfb4ff7c7236fd84aae4ab706d887

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

module ObjectInspector
  # ObjectInspector::ObjectInterrogator collaborates with {#object} to return
  # Object#{#method_name} if {#object} responds to the method.
  #
  # If Object#{#method_name} accepts the supplied {#kargs} then they are passed
  # in as well. If not, then any supplied {#kargs} will be ignored.
  class ObjectInterrogator
    attr_reader :object,
                :method_name,
                :kargs

    def initialize(object:, method_name:, kargs: {})
      @object = object
      @method_name = method_name
      @kargs = kargs
    end

    # @return [String, ...] whatever type Object#{#method} returns
    #
    # @raise [ArgumentError] if Object#{#method} has an unexpected method
    #   signature
    def call
      return unless object_responds_to_method_name?

      if object.method(method_name).arity != 0
        call_with_kargs
      else
        object.send(method_name)
      end
    end

    private

    def call_with_kargs
      object.send(method_name, **kargs)
    rescue ArgumentError
      object.send(method_name)
    end

    def object_responds_to_method_name?(include_private: true)
      object.respond_to?(method_name, include_private)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
object_inspector-0.5.2 lib/object_inspector/object_interrogator.rb