Ruby refinements and hooks
Asked Answered
W

1

8

I'm trying to use ruby refinements to apply rails hooks.

I want to avoid monkey patching. When monkey patching it would work as such

ActiveRecord::Base.class_eval do
  after_find do 
     # do something with 
     my_method
  end

  def my_method
    # something useful
  end
end

I've been able to have the class method by doing something like such:

module ActiveRecordRefinements
  refine ActiveRecord::Base.singleton_class do
    def my_method
     #something cool
    end
  end
end

But I can't run the hook. I tried using self.used(klass) but don't seem to be able to get the syntax just right.

Any help is welcome.

Thanks.

Window answered 31/8, 2015 at 16:32 Comment(3)
You don't need to call #singleton_class on ActiveRecord::Base since refinements are singletons.Attainder
I'm trying to add to the DSL of AR. Something like ``` class Foo < AR::Base using ActiveRecordRefinements my_method :my_stuff end ``` Since I'm not adding methods to an object (well, a singleton object), I found that I did need the singleton_classWindow
There's a fine line between monkey patching and dependency injection. Normally monkey patching is defined as redefining core behaviour in a manner that's not necessarily going to work with future versions of the core. A cleaner dependency injection model tries to avoid conflict and maintain a minimal footprint.Overmaster
T
0

There is a reason you're not using ActiveSupport Callbacks? Take a look here: http://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html

Tamarah answered 19/7, 2016 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.