Ruby pro tips from Rails core committer Aaron Patterson

WHERE IS THAT METHOD?

Q: This code is calling a method, but I don't know where the method is defined. How can I find it?
A: Use the method method. The method method will return a method object and let you callsource_location to find the method location. For example:
p object.method(:unknown_method).source_location
If object has the instance method unknown_method, this code will print the location of that method.

WHO IS CALLING ME?

Q: I'm inside a method, but I don't know who called this method. How can I find out?
A: Use the caller method. The caller method will give you the current stack trace, so you can do p caller and see who is calling you. Alternatively, just raise an exception, and you'll see the backtrace.

WHAT IS MY CLASS?

Q: I'm editing a method, but I'm not sure what class it's defined on. How can I find out?
A: Use the class method. For example:
def foo
  p self.class
end
This will print out the class of self which is your current instance.

WHAT IS MY SUPERCLASS?

Q: I am editing a method that calls super, like this:
def foo
  # ...
  super
  # ...
end
I want to know where the superclass method is defined. How do I find it?
A: You can use the superclass method on the class to get the superclass. For example:
def foo
  # ...
  p self.class.superclass.instance_method(:foo).source_location
  super
  # ...
end
One caveat is that the method may not be defined on your superclass, but somewhere further up the inheritance chain. You can find that by using ancestors. For example:
def foo
  # ...
  self.class.ancestors.each do |klass|
    next unless klass.method_defined?(:foo)
    p klass.instance_method(:foo).source_location
  end
  super
  # ...
end

I NEED A DEBUGGER!

I personally don't use a debugger, but I've heard the debugger gem is good.

Source: edx online BerkleyX course (saas engineering cs169x.1)

Comments

  1. Koreans can't gamble at casinos— with one exception I’ll mention later. Do not underestimate this because of|as a outcome of} this shapes the complete playing culture here. Kangwon Land ducked underneath the government cap final yr by US$63 million, with income down 8% from a yr earlier, operating profit down 31% and visitation down 8% to 2.85 million. Active measures to crimp on line casino take embrace cutting the desk count from 200 to one hundred eighty , restricting VIP memberships and decreasing casino 우리카지노 계열 operations by two hours to 10 a.m.-4 a.m. To try to reverse declines, but not extreme amount of}, administration final month shifted operating hours to 12 noon-6 a.m.

    ReplyDelete

Post a Comment