Module: MethodSource::MethodExtensions

Included in:
Method, Proc, UnboundMethod
Defined in:
lib/method_source.rb

Overview

This module is to be included by ‘Method` and `UnboundMethod` and provides the `#source` functionality

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

We use the included hook to patch Method#source on rubinius. We need to use the included hook as Rubinius defines a ‘source` on Method so including a module will have no effect (as it’s higher up the MRO).

Parameters:

  • klass (Class)

    The class that includes the module.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/method_source.rb', line 100

def self.included(klass)
  if klass.method_defined?(:source) && Object.const_defined?(:RUBY_ENGINE) &&
      RUBY_ENGINE =~ /rbx/

    klass.class_eval do
      orig_source = instance_method(:source)
      
      define_method(:source) do
        begin
          super
        rescue
          orig_source.bind(self).call
        end
      end
      
      end
    end
end

Instance Method Details

#commentString

Return the comments associated with the method as a string. (This functionality is only supported in Ruby 1.9 and above)

Examples:

Set.instance_method(:clear).comment.display
=>
   # Removes all elements and returns self.

Returns:

  • (String)

    The method’s comments as a string



148
149
150
151
152
153
154
155
156
157
158
# File 'lib/method_source.rb', line 148

def comment
  if respond_to?(:source_location)
    comment = MethodSource.comment_helper(source_location)
    
    raise "Cannot locate source for this method: #{name}" if !comment
  else
    raise "#{self.class}#comment not supported by this Ruby version (#{RUBY_VERSION})"
  end

  comment
end

#sourceString

Return the sourcecode for the method as a string (This functionality is only supported in Ruby 1.9 and above)

Examples:

Set.instance_method(:clear).source.display
=>
   def clear
     @hash.clear
     self
   end

Returns:

  • (String)

    The method sourcecode as a string



129
130
131
132
133
134
135
136
137
138
139
# File 'lib/method_source.rb', line 129

def source
  if respond_to?(:source_location)
    source = MethodSource.source_helper(source_location)
    
    raise "Cannot locate source for this method: #{name}" if !source
  else
    raise "#{self.class}#source not supported by this Ruby version (#{RUBY_VERSION})"
  end
  
  source
end