Sha256: 5b077549c79789c46c16f7930b2550600ca0c2ead230c093bb78331ebc6758fd

Contents?: true

Size: 947 Bytes

Versions: 4

Compression:

Stored size: 947 Bytes

Contents

module JSONAPIonify::DestructuredProc
  refine Proc do
    def destructure(at_index = -1, object: nil)
      return self unless kwargs.present?
      original = self
      Proc.new do |*args|
        kwargs = original.kwargs_destructured(object || args[at_index])
        JSONAPIonify::CustomRescue.perform(remove: __FILE__, source: original, formatter: ->(meta) { meta.source_location.join(':') + ":in `block (destructured)'" }) do
          instance_exec(*args, **kwargs, &original)
        end
      end
    end

    def kwargs
      parameters.select { |t, k| t.to_s.start_with?('key') && !t.to_s.end_with?('rest') }
    end

    def arguments
      parameters.reject { |t, k| t.to_s.start_with?('key') || t.to_s.end_with?('rest') }
    end

    def kwargs_destructured(target)
      kwargs.each_with_object({}) do |(_, key), kw|
        next unless target.respond_to? key
        kw[key] = target.public_send(key)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
jsonapionify-0.12.10 lib/jsonapionify/destructured_proc.rb
jsonapionify-0.12.9 lib/jsonapionify/destructured_proc.rb
jsonapionify-0.12.8 lib/jsonapionify/destructured_proc.rb
jsonapionify-0.12.7 lib/jsonapionify/destructured_proc.rb