-1

I want to find a gem or to write a code that implements hooks for methods.

class A
  include SomeModule
  before_hook :meth, lambda { puts 'bla' }

  def meth
    puts 'meth'
  end
end

# A.new.meth => "bla\nmeth\n"

I am using Rails and I know about callbacks and filters but

  • meth isn't an action
  • I don't wand to change how I method call

Help me please...

UPDATE

I find a gem for automating this code:

  include ActiveSupport::Callbacks
  define_callbacks :meth_callback

  set_callback :meth_callback, :before do |object|
    # my code
  end

  def meth_with_callback
    run_callbacks(:meth_callback) { meth }
  end

  alias_method_chain :meth, :callback
Kuraga
  • 331
  • 3
  • 16
  • possible duplicate of [Defining "method_called".. How do I make a hook method which gets called every time any function of a class gets called?](http://stackoverflow.com/questions/3236194/defining-method-called-how-do-i-make-a-hook-method-which-gets-called-every-t) – Peter Brown Jun 10 '12 at 13:02
  • 1
    Take a look http://stackoverflow.com/a/10471857/1322562 – jdoe Jun 10 '12 at 13:04
  • @jdoe Yes that's it what I want but isn't there a gem whit this functionality? – Kuraga Jun 10 '12 at 13:19
  • @АлександрКуракин - you will get better answers if you go back and accept answers to your previous questions. – Mark Reed Jun 10 '12 at 13:42
  • @АлександрКуракин This is too simple task for a gem. It's already a part of Rails. What would any one want to extract it?.. – jdoe Jun 10 '12 at 13:57
  • @jdoe, I don't think there's some kind of minimum complexity for gems. Small libraries that do one thing well are a good thing; if ActiveSupport was broken up into small parts, people would be able to use what they actually wanted to use without having to depend on the entire thing. – Matheus Moreira Jun 10 '12 at 15:05

1 Answers1

5

You can use ActiveModel::Callbacks

define_model_callbacks :create

def create
  run_callbacks :create do
    # do your thing here
  end
end

You can even write a little helper method to hide this run_callbacks line. It may look like this:

hooked_method :create do
  # do your thing here
end
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367