Sha256: 0f364da3dda08d2c049ac5b5775551d987b79de18e39bb76881d420e32fedd6e

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 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)
      return @parent.public_send(name, *args) if %i[__ g].include?(name) && !@parent.nil?

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

      return wrap_result(instance_exec(*args, &@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

2 entries across 2 versions & 1 rubygems

Version Path
grumlin-0.13.1 lib/grumlin/shortcut_proxy.rb
grumlin-0.13.0 lib/grumlin/shortcut_proxy.rb