Pattern matching in Ruby is not a well understood or frequently used feature, but when paired with ASTs it becomes an incredibly powerful tool for refactoring and code transformations.
This talk is a deep dive into ASTs and RuboCop as refactoring and upgrade tools. With the advent of language servers this will become a very critical topic to have knowledge in to effectively work with manipulating Ruby code programatically.
Intermediate to Advanced. If you're programatically manipulating Ruby syntax you're very likely in an advanced category, but some intermediate developers may get value from this talk as well.
- Immediately applicable knowledge of common ASTs (syntax_tree, Whitequark, Ripper)
- Immediately applicable usage of
TreeRewriter
for refactoring
- Introduction
- On ASTs
- Evolution of Ripper to Whitequark to now syntax_tree
- Evolution of rewriters (RuboCop, TreeRewriter, etc)
- Tools
- Overview of Array-like pattern matching
- Deep deconstruction of source code to AST-like representation
- Language server integrations
- Practical Implementation
- Task: Rewrite
[1,2,3].select { |v| v.even? }
to[1,2,3].select(&:even?)
- Deconstruct to AST (example in stree, whitequark)
- Reconstruction using capture groups
- Rewriting file using
TreeRewriter
- Task: Rewrite
- The Future
- AST searching, wildcards, code "like this"
MyAPI.call(1, _, _)
likeMyAPI.call(1, 2, 3)
- "Did you mean" can pull from existing code samples "like" what someone is writing
- Does someone have existing code close to what you're trying to write?
- Is the code you're trying to write in a method somewhere, or similar to one?
- Auto Test Writing
- You added a branch case, mimic existing formatting to write "new test" for that branch in RSpec
- A to B refactors: Any code that looks like string "A" should be refactored to "B"
- Tree diffing, PhD level problem, probably not easily possible
- AST searching, wildcards, code "like this"
- Wrapping Up
- The future is ASTs
- Ruby tooling relies on strong knowledge here
- Pattern matching is one of the most powerful tools we have
- Go out and build
I have written extensively on both pattern matching as well as ASTs in Ruby, and wish to share this knowledge on a stage with advanced Ruby developers who are likely to build tools using that knowledge. I believe we have only scratched the surface of what is possible with this technology and want to inspire others as to those potentials. "The Future" section here has a lot more potential, and will be the subject of my research in preparing this talk should it be selected.