Sha256: 5b49e8b6fd8b6f503a6c02196bb11888be89a9fd54f2e9b74bca42d0204ebcf8

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Grumlin
  class ShortcutProxy
    extend Forwardable

    attr_reader :object, :shortcuts

    # shortcuts: {"name": ->(arg) {}}
    def initialize(object, shortcuts, parent: nil)
      @object = object
      @shortcuts = shortcuts
      @parent = parent
    end

    def method_missing(name, *args, **params)
      return @parent.public_send(name, *args, **params) if %i[__ g].include?(name) && !@parent.nil?

      return wrap_result(@object.public_send(name, *args, **params)) if @object.respond_to?(name)

      return wrap_result(instance_exec(*args, **params, &@shortcuts[name])) if @shortcuts.key?(name)

      super
    end

    # For some reason the interpreter thinks it's private
    public def respond_to_missing?(name, include_private = false) # rubocop:disable Style/AccessModifierDeclarations
      name = name.to_sym

      (%i[__ g].include?(name) &&
      @parent.respond_to?(name)) ||
      @object.respond_to?(name) ||
      @shortcuts.key?(name) ||
      super
    end

    def_delegator :@object, :to_s

    def inspect
      @object.inspect
    end

    private

    def wrap_result(result)
      return self.class.new(result, @shortcuts, parent: @parent) if result.is_a?(AnonymousStep)

      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
grumlin-0.14.0 lib/grumlin/shortcut_proxy.rb