Skip to content

Instantly share code, notes, and snippets.

@misfo
Created September 2, 2013 04:04
Show Gist options
  • Save misfo/6409140 to your computer and use it in GitHub Desktop.
Save misfo/6409140 to your computer and use it in GitHub Desktop.
require 'unparser'
original_verbosity = $VERBOSE
$VERBOSE = nil
Unparser::Emitter::REGISTRY = Unparser::Emitter::REGISTRY.dup
$VERBOSE = original_verbosity
module Rbfmt
module Emitters
# * Uses parens if the source did
class Send < Unparser::Emitter::Send
handle :send
private
def parenthesize?
node.loc.begin
end
def emit_arguments
args = arguments
return if args.empty?
if parenthesize?
parentheses { delimited(args) }
else
write ' '
delimited(args)
end
end
end
# * Supports `elsif` keyword
# * Uses postfix notation if the source did.
class If < Unparser::Emitter::If
handle :if
private
def dispatch
return PostfixIf.emit(node, buffer, self) if postfix?
write(keyword, WS)
emit_condition
emit_if_branch
emit_else_branch
k_end
end
def postfix?
return false unless node.loc.is_a?(Parser::Source::Map::Keyword)
branch = unless? ? else_branch : if_branch
node.loc.keyword.begin_pos > branch.loc.expression.begin_pos
end
def elsif_branch?
else_branch.type == :if &&
else_branch.loc.is_a?(Parser::Source::Map::Condition) &&
else_branch.loc.keyword.source == K_ELSIF
end
def emit_else_branch
return unless else_branch
if elsif_branch?
Elsif.emit(else_branch, buffer, self)
else
write(K_ELSE) unless unless?
visit_indented(else_branch)
end
end
class Elsif < self
private
def dispatch
write(K_ELSIF, WS)
emit_condition
emit_if_branch
emit_else_branch
end
end
class PostfixIf < self
private
def dispatch
visit(unless? ? else_branch : if_branch)
write(WS, keyword, WS)
emit_condition
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment