yeputons
yeputons

Reputation: 9238

Is there a way to check what's inside method's code in Ruby or even modify it?

I'm currently creating a my own plugin for Redmine. I found the following method in its core (not exact code, but the idea is preserved):

def method(foo, bar, array)
    # Do some complex stuff with foo and bar

    @array = array
    @array.uniq!
    @array = @array[0:3]

    # Do some complex weird stuff with @array
end

I have to change this '3' to '6', because three elements in array is not enough for my plugin's purposes. I can change it manually and nothing crashes, but I don't want to patch Redmine's core. So, I'm writing a plugin which replaces this method with my own implementation, which does the same thing, but three is changed to six.

Here's the problem: if this file updates, outdated method will be used. Is there any way to check what's written inside method in runtime (for example, when server starts)?

By the way, is there any method to directly modify this constant without overriding the whole method?

Upvotes: 3

Views: 108

Answers (2)

sawa
sawa

Reputation: 168101

If you are able to access the file, then you can use the pry gem to check the source code. Or without such gem, you can manually check the location of the method by doing puts method(:foo).source_location, and read that part.

The easiest for you to change the behaviour is to override the entire method.

Upvotes: 1

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

No, there is no way to get a method's source code at runtime in Ruby. On some Ruby implementations there may be a way to get the source code which works some of the time, but that will be neither reliable nor portable. After all, there isn't even a guarantee that the source code will even be Ruby, since most implementations allow you to write methods in languages other than Ruby (e.g. C in YARV, Java in JRuby etc.)

Upvotes: 1

Related Questions