Sha256: 8c34a4779cc1d0ec01610a599c8a8c15922e9e31a7d19eda952a7692deede19d

Contents?: true

Size: 1.18 KB

Versions: 3

Compression:

Stored size: 1.18 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

    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

3 entries across 3 versions & 1 rubygems

Version Path
object_inspector-0.6.2 lib/object_inspector/object_interrogator.rb
object_inspector-0.6.1 lib/object_inspector/object_interrogator.rb
object_inspector-0.6.0 lib/object_inspector/object_interrogator.rb