1

I want to know what method updates my object. I have ActiveRecord class Event, with column method_name in it. Is there some way to save caller method in that column after my object was updated?

Update

I though about something like this:

class Event
  after_save :set_caller

  def set_caller
    self.update(method_name: caller)
  end
end

But at this moment caller is active_support/callbacks.rb

yozzz
  • 1,267
  • 1
  • 22
  • 30
  • 1
    You know how to get caller method name. You also know (presumably) how to update an activerecord object. What's the problem here? – Sergio Tulentsev Jul 03 '15 at 09:53
  • One method saves your object, and that method in turn, calls another method to save your object, and the chain may be even longer. What would method do you want to save at the end? The first one or the last one? – Arslan Ali Jul 03 '15 at 10:03
  • You might use [`after_commit`](https://github.com/rails/rails/commit/da840d13da865331297d5287391231b1ed39721b) callback to get [`#caller`](http://ruby-doc.org/core-2.2.2/Kernel.html#method-i-caller) and store it somewhere. – Aleksei Matiushkin Jul 03 '15 at 10:03
  • @SergioTulentsev, the thing is that i don't know how to get caller method name – yozzz Jul 03 '15 at 10:14
  • @yozzz: easy. Just use `caller` method! It'll return a stack trace. You probably only want the first line. It contains file/line info too, so you'll want to extract method name from it with regex or something – Sergio Tulentsev Jul 03 '15 at 10:19
  • @mudasobwa: won't `caller` in `after_commit` show just 200 lines of AR internals? – Sergio Tulentsev Jul 03 '15 at 10:20
  • @SergioTulentsev Good point. It likely will. Hmmm. Will check :) – Aleksei Matiushkin Jul 03 '15 at 10:26
  • @yozzz: "But at this moment caller is active_support/callbacks.rb" - obviously. Because it's a callback. Called by ActiveRecord. Use `caller` in `update` or `save` or whichever method you use to save an object – Sergio Tulentsev Jul 03 '15 at 10:30
  • @SergioTulentsev about example that I provide, as you say it returns over 200 lines of AR internals and others methods – yozzz Jul 03 '15 at 10:31
  • @SergioTulentsev i understand, but there so many places, that can update object. I can miss something... – yozzz Jul 03 '15 at 10:33
  • 1
    If you control the calling code, you should know all the methods you use. Also here's a tip: in output of `caller`, skip all the AR stuff and find the first line from your app files. It'll likely be the caller you need. – Sergio Tulentsev Jul 03 '15 at 10:37
  • @SergioTulentsev Yes, filtering by `/\A#{Rails.root}/` does the trick. – Aleksei Matiushkin Jul 03 '15 at 10:50

1 Answers1

0

the thing is that i don't know how to get caller method name

How to get the name of the calling method?

You could use

caller[0][/`.*'/][1..-2]
Community
  • 1
  • 1
BinaryMee
  • 2,102
  • 5
  • 27
  • 46