Using XPath to rewrite Ruby code with ease

Lucas Luitjes
Ruby Inside
Published in
2 min readNov 26, 2017

I’m moving my blog to a self-hosted alternative, you can find the rest of this post here: https://blog.luitjes.it/posts/using-xpath-to-rewrite-ruby-code-with-ease/

Tools that rewrite Ruby code, such as rubocop, do so by using the excellent parser gem. The parser gem allows you to convert your Ruby code into an AST (abstract syntax tree). For a primer on this topic, see the introduction to the parser gem.

While building textractor we often found ourselves writing code to query and filter ASTs to find the exact node to modify. For example to programmatically turn <%= f.text_field :name, placeholder: "Your name" %> into <%= f.text_field :name, placeholder: t('.your_name') %> we need to find the node of the value for the placeholder key, in a hash that happens to be an argument for a text_field call.

It turns out there is already an excellent query language for searching tree structures: XPath! All we have to do is turn an AST into an XML tree, run the XPath query, and find the original AST node belonging to the matches.

I’m moving my blog to a self-hosted alternative, you can find the rest of this post here: https://blog.luitjes.it/posts/using-xpath-to-rewrite-ruby-code-with-ease/

--

--