0

I am looking at this answer to monkey-patch https://stackoverflow.com/a/21446021.

In this example the gem (someone else's library) has the method someMethod() which will eventually call the method I patched.

My app looks like this

activeRecord = ... # gets an ActiveRecord object that I want to update 
options = {..}
@gem_object = SomeLibrary::Class.new(options)

@gem_object.someMethod()

Now someMethod() is going to eventually call the patched method. I want to make the patched method aware of activeRecord so it can update it. I am wondering if I can avoid adding activeRecord as a parameter to all the methods in the stack-trace when someMethod() is called.

Community
  • 1
  • 1
gravitas
  • 703
  • 4
  • 16
  • I don't there there's any reason to pass the object around. You can access your models in the patched method. – max pleaner Mar 19 '16 at 01:19
  • Wouldn't that re-run the SQL? In my app I already have an instantiation of the active record object. – gravitas Mar 19 '16 at 01:21
  • it would re-run the SQL, but is that really such a bad thing? Really how much performance do you gain by making the query once vs twice? You can see the query time in your rails console - simple queries take milliseconds. – max pleaner Mar 19 '16 at 01:25

1 Answers1

2

I'd store it in a plain class

class StoreRecord
  def self.activeRecord
    @active_record
  end
  def self.activeRecord=(record)
    @active_record = record
  end
end

so your code becomes

StoreRecord.activeRecord = ... # gets an ActiveRecord object that I want to update 
options = {..}
@gem_object = SomeLibrary::Class.new(options)

@gem_object.someMethod()

and you can access StoreRecord.activeRecord in your patched method.

SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53