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.

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Max
  • 156
  • 1
  • 2
    You don't need to call `#singleton_class` on `ActiveRecord::Base` since refinements are singletons. – Nathan Aug 31 '15 at 16:35
  • 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_class – Max Aug 31 '15 at 16:38
  • 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. – tadman Sep 30 '15 at 21:46

1 Answers1

0

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

Jacopo Beschi
  • 178
  • 2
  • 6