Class: RubyTransform::Transformers::SymbolNames

Inherits:
RubyTransform::Transformer show all
Defined in:
lib/ruby_transform/transformers/symbol_names.rb

Overview

Symbol Names

Sometimes you’ll come across code written by a Java developer who uses camel-cased names for variables and methods. This transformer will allow you to apply some transformation (defined through a block to initialize) to every symbol name in the application, which includes all of these:

  • Method Names (Definitions and Calls)

  • Local Variable Names

  • Instance Variable Names

  • Class Variable Names

Big Caveat: This transformer does not detect instances where the symbol name is referenced inside an eval-ed string, for example when you are instance_evaling some large string. As always, run your tests after any transformation.

Example:

# Underscores symbol names
RubyTransform::Transformers::SymbolNames.new {|name| name.underscore }

# Given This:
def myMethod
  myVariable = 1
  @iVar = myMethod(myVariable)
end

# Translates to This:
def my_method
  my_variable = 1
  @i_var = my_method(my_variable)
end

# Or maybe translate from English to French
RubyTransform::Transformers::SymbolNames.new {|name| Google::Translate.new(:fr).translate(name) }

Instance Method Summary collapse

Methods included from RubyTransform::TransformerHelpers

#sexp?

Constructor Details

#initialize(&block) ⇒ SymbolNames

Returns a new instance of SymbolNames.



37
38
39
# File 'lib/ruby_transform/transformers/symbol_names.rb', line 37

def initialize(&block)
  @name_transformer = block
end

Instance Method Details

#transform(e) ⇒ Object



41
42
43
# File 'lib/ruby_transform/transformers/symbol_names.rb', line 41

def transform(e)
  super(transform_symbols(e))
end

#transform_symbols(e) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ruby_transform/transformers/symbol_names.rb', line 45

def transform_symbols(e)
  return e unless sexp?(e)
  
  case e.kind
  when :defn
    e.clone.tap {|c| c[1] = @name_transformer.call(c[1].to_s).to_sym }
  when :defs
    e.clone.tap {|c| c[2] = @name_transformer.call(c[2].to_s).to_sym }
  when :call
    e.clone.tap {|c| c[2] = @name_transformer.call(c[2].to_s).to_sym }
  when :lasgn, :lvar
    e.clone.tap {|c| c[1] = @name_transformer.call(c[1].to_s).to_sym }
  when :cvdecl, :cvasgn, :cvar
    e.clone.tap {|c| c[1] = ("@@" + @name_transformer.call(c[1].to_s.gsub(/^@@/, ''))).to_sym }
  when :iasgn, :ivar
    e.clone.tap {|c| c[1] = ("@" + @name_transformer.call(c[1].to_s.gsub(/^@/, ''))).to_sym }
  else
    e
  end
end