aadeshere1
aadeshere1

Reputation: 95

How to call private method just before another method completes execution?

I have two methods in rails

def foo
    puts "foo"
    find_article
end

def bar
    puts "bar"
    find_article
end

private
def find_article
    do_something
end

Is there a way to call find_article without specifying in foo and bar ?

Upvotes: 0

Views: 874

Answers (3)

Kris
Kris

Reputation: 19948

If this is Rails then after_action:

class MyController
  after_action :find_article

  def foo
    puts "foo"
  end

  def bar
    puts "bar"
  end

  private

  def find_article
    do_something
  end
end

Upvotes: 0

Lewis Jones
Lewis Jones

Reputation: 236

Rails includes a way to do this with ActiveModel::Callbacks http://api.rubyonrails.org/classes/ActiveModel/Callbacks.html

class FooBar
  extend ActiveModel::Callbacks
  define_model_callbacks :foobar
  after_foobar :find_article

  def foo
    run_callbacks :foobar do
      puts "foo"
    end
  end

  def bar
    run_callbacks :foobar do
      puts "bar"
    end
  end

  private

  def find_article
    puts 'finding article'
  end
end

result:

[1] pry(main)> FooBar.new.foo
foo
finding article
=> nil
[2] pry(main)> FooBar.new.bar
bar
finding article
=> nil

Upvotes: 2

kiddorails
kiddorails

Reputation: 13014

Something in the lines of:

module Magic
  def after_method(original, callback)
    all = [*original]
    all.each do |original|
      m = instance_method(original)
      define_method(original) do |*args, &block|
        m.bind(self).(*args, &block)
        send(callback)
      end
    end
  end
end


class X
  extend Magic
  def foo
    puts "foo"
  end

  def bar
    puts "bar"
  end

  private
  def find_article
    puts "DONE"
  end

  after_method [:foo, :bar], :find_article    
end
X.new.foo
# foo
# done

Got little help from here

Upvotes: 0

Related Questions