0

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 ?

aadeshere1
  • 65
  • 1
  • 9

3 Answers3

2

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
Lewis Jones
  • 236
  • 1
  • 7
0

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

kiddorails
  • 12,961
  • 2
  • 32
  • 41
0

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
Kris
  • 19,188
  • 9
  • 91
  • 111
  • If I replace `do_something` with `render template`, it will try to call render function two times, which is invalid. – aadeshere1 Nov 09 '17 at 16:39
  • It shouldn't, try just putting `find_article` after the `puts` without using `before_action` and see if the same happens. – Kris Nov 10 '17 at 12:22
  • Right kris, it works if I put `find_article` after `puts`, but I have to do same thing for 3 different controllers and each controller have 3-4 methods in them. – aadeshere1 Nov 11 '17 at 11:50
  • I meant to try it to see if it calls render twice, because using `after_action` is effectively the same thing. – Kris Nov 13 '17 at 14:27