Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active Jan 8, 2021
Embed
What would you like to do?
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