Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active January 8, 2021 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inopinatus/1630f5a0ca3cc753496e60ae757d000e to your computer and use it in GitHub Desktop.
Save inopinatus/1630f5a0ca3cc753496e60ae757d000e to your computer and use it in GitHub Desktop.
Abusing pattern matching as a proc factory and subsequent invocation
# frozen_string_literal: true
require 'json'
module Proxy
refine Object do
def deconstruct_keys(methods)
methods.to_h { |m| [m, ->(*a) { throw m, public_send(m, *a) }] }
end
end
end
class MyApp
using Proxy
attr_reader :parser
def initialize
JSON => {parse: parser}
@parser = parser
end
end
# Later that same program....
parser = MyApp.new.parser
# Obtain input
str = '{ "foo": [1,2,null] }'
# Parse
res = catch(:parse) { str => ^parser }
puts "result: #{res.inspect}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment