Sha256: e2d53c7c67379e9395fe1d541e676e631d92f419d6353c6e22eb7fdf59bb31b6

Contents?: true

Size: 1.5 KB

Versions: 36

Compression:

Stored size: 1.5 KB

Contents

module DuckPuncher
  module Ducks
    module Method
      def to_instruct
        definition = Definition.new(self)
        RubyVM::InstructionSequence.new(definition.lines.join).disasm if definition.lines.any?
      end

      def to_source
        Definition.new(self).to_s
      end

      class Definition
        def initialize(method_handle)
          @file_path, @line_num = *method_handle.source_location
          @line_num = @line_num.to_i
        end

        # @description finds the method's source code using the indent size of the file. This means we are
        # restricted when it comes to parsing crappy formatted ruby files
        def lines
          return @lines if defined? @lines
          return [] unless @file_path
          @lines = []
          File.open(@file_path) do |f|
            found = false
            i = 0
            while line = f.gets and i += 1 and !found
              next if i < @line_num
              @lines << line
              if @indent_size
                found = @indent_size == find_indent_size(line)
              else
                @indent_size = find_indent_size(line)
                found = line.end_with?("end\n")
              end
            end
          end
          @lines
        end

        def to_s
          if lines.any?
            lines.join.gsub /^\s{#{find_indent_size(lines.first)}}/, ''
          else
            ''
          end
        end

        def find_indent_size(line)
          line[/(\s*)/].size
        end
      end
    end
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
duck_puncher-5.0.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.5.1 lib/duck_puncher/ducks/method.rb
duck_puncher-4.5.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.4.2 lib/duck_puncher/ducks/method.rb
duck_puncher-4.4.1 lib/duck_puncher/ducks/method.rb
duck_puncher-4.4.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.3.1 lib/duck_puncher/ducks/method.rb
duck_puncher-4.3.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.2.3 lib/duck_puncher/ducks/method.rb
duck_puncher-4.2.2 lib/duck_puncher/ducks/method.rb
duck_puncher-4.2.1 lib/duck_puncher/ducks/method.rb
duck_puncher-4.2.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.1.0 lib/duck_puncher/ducks/method.rb
duck_puncher-4.0.0 lib/duck_puncher/ducks/method.rb
duck_puncher-3.0.0 lib/duck_puncher/ducks/method.rb
duck_puncher-2.16.0 lib/duck_puncher/ducks/method.rb
duck_puncher-2.15.0 lib/duck_puncher/ducks/method.rb
duck_puncher-2.14.1 lib/duck_puncher/ducks/method.rb
duck_puncher-2.14.0 lib/duck_puncher/ducks/method.rb
duck_puncher-2.13.0 lib/duck_puncher/ducks/method.rb