我在rails中有两种方法
def foo
puts "foo"
find_article
end
def bar
puts "bar"
find_article
end
private
def find_article
do_something
end
有没有办法调用find_article而无需在foo
和bar
中指定?
答案 0 :(得分:1)
Rails包含了一种使用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
结果:
[1] pry(main)> FooBar.new.foo
foo
finding article
=> nil
[2] pry(main)> FooBar.new.bar
bar
finding article
=> nil
答案 1 :(得分:0)
以下内容:
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
的帮助很少
答案 2 :(得分:0)
如果这是Rails,那么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