-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactors rewriter into its own file
- Loading branch information
Showing
2 changed files
with
48 additions
and
36 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# frozen_string_literal: true | ||
|
||
module Rubyists | ||
module Namespacer | ||
# Do the AST rewriting with the Rewriter class | ||
class Rewriter < Parser::TreeRewriter | ||
attr_accessor(:namespaces) | ||
|
||
def initialize(namespaces) | ||
super() | ||
@namespaces = namespaces | ||
end | ||
|
||
def on_module(node) | ||
_on_module(node) | ||
end | ||
|
||
def on_class(node) | ||
_on_module(node) | ||
end | ||
|
||
private | ||
|
||
def wrap(ast) | ||
# Recursively wrap the AST in the namespace modules | ||
namespaces.split('::').reverse.inject(ast) do |current_ast, ns| | ||
# Create a module node with the current namespace part and the current AST | ||
Parser::AST::Node.new(:module, [Parser::AST::Node.new(:const, [nil, ns.to_sym]), current_ast]) | ||
end | ||
end | ||
|
||
def _on_module(node) | ||
return unless node.location.column.zero? | ||
|
||
(ast, comments) = Unparser.parse_with_comments(node.location.expression.source) | ||
replace(node.location.expression, Unparser.unparse(wrap(ast), comments)) | ||
end | ||
end | ||
end | ||
end |