-3

I cannot follow what caller does in these exception raising statements.

raise InterfaceException , "Error", caller

raise ArgumentError, " Error", caller[1..-1]

I know that Object#caller sets and sends stack trace to upper level in hierarchy. What is the interpretation of the arguments 1..-1 of the method caller?

sawa
  • 165,429
  • 45
  • 277
  • 381
Sukhbir
  • 553
  • 8
  • 23
  • There is no such thing as `Object#caller`. `1..-1` is not argument**s**, it is a single `Range` argument. – sawa Dec 19 '15 at 13:24
  • @sawa: Well, technically, objects _do_ respond to `caller`. – Sergio Tulentsev Dec 19 '15 at 13:29
  • @SergioTulentsev Right, but is that what `Object#caller` means? – sawa Dec 19 '15 at 13:30
  • @sawa: I think it is. The fact that actual implementation is inherited is not very relevant. People say stuff like `User#create` all the time, despite the fact that the implementation resides somewhere in the bowels of active record. – Sergio Tulentsev Dec 19 '15 at 13:32

1 Answers1

2

As you noted, caller returns current stack trace (not including current method). caller[1..-1] returns the stacktrace, minus its first entry.

Might be useful in some situations. For example you set up a params validation handler (or whatever) and it can raise. But you don't want to see the error originate in the validation handler. You want the line that called it.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 3
    using `caller` will exclude the current method from the stack trace you'd see if you just did plain old `raise InterfaceException, "Error"` and so using `caller[1..-1]` will be removing the top 2 entries from the default behaviour. – mikej Dec 19 '15 at 13:34
  • @mikej: yes, you're correct. Realized that after running wandmaker's code. The idea is still the same: ignoring last elements of the stacktrace. Sometimes you skip one line, sometimes more. – Sergio Tulentsev Dec 19 '15 at 13:39