Class: LetItGo::WTFParser

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/let_it_go/wtf_parser.rb

Overview

Used for parsing the output of Ripper from a single line of Ruby.

Pulls out method calls, and arguments to those method calls. We only care about when a string literal isn’t frozen

Defined Under Namespace

Classes: BinaryCall, CommandCall, MethodAdd

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ripped_code, contents: "") ⇒ WTFParser

Returns a new instance of WTFParser.



173
174
175
176
# File 'lib/let_it_go/wtf_parser.rb', line 173

def initialize(ripped_code, contents: "")
  @contents   = contents
  @raw = ripped_code || []
end

Instance Attribute Details

#contentsObject

Returns the value of attribute contents.



171
172
173
# File 'lib/let_it_go/wtf_parser.rb', line 171

def contents
  @contents
end

Instance Method Details

#all_methodsObject Also known as: method_add



198
199
200
201
202
203
204
# File 'lib/let_it_go/wtf_parser.rb', line 198

def all_methods
  @method_add_array ||= begin
    method_add_array = []
    find_method_add_from_raw(@raw.dup, method_add_array)
    method_add_array
  end
end

#eachObject Also known as: each_method



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/let_it_go/wtf_parser.rb', line 207

def each
  begin
    if block_given?
      all_methods.each do |obj|
        begin
          yield obj
        rescue => e
        end
      end
    else
      enum_for(:each)
    end
  rescue => e
    msg = "Could not parse seemingly valid Ruby code:\n\n"
    msg << "    #{ parser.contents.inspect }\n\n"
    msg << e.message
    raise e, msg
  end
end

#find_method_add_from_raw(ripped_code, array = []) ⇒ Object

Parses raw input recursively looking for :method_add_arg blocks



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/let_it_go/wtf_parser.rb', line 179

def find_method_add_from_raw(ripped_code, array = [])
  return false unless ripped_code.is_a?(Array)

  case ripped_code.first
  when :method_add_arg
    array << MethodAdd.new(ripped_code)
    ripped_code.shift
  when :command_call
    array << CommandCall.new(ripped_code)
    ripped_code.shift
  when :binary
    array << BinaryCall.new(ripped_code)
    ripped_code.shift
  end
  ripped_code.each do |code|
    find_method_add_from_raw(code, array) unless ripped_code.empty?
  end
end