Last active
January 8, 2021 02:16
-
-
Save inopinatus/1630f5a0ca3cc753496e60ae757d000e to your computer and use it in GitHub Desktop.
Abusing pattern matching as a proc factory and subsequent invocation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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