简体   繁体   English

带传递参数的rails中的around_action?

[英]around_action in rails with passing arguments?

How to call around_action in Rails which accepts arguments ?如何在接受参数的 Rails 中调用around_action

around_action only: [:follow] do
 set_follow_source(@source)
end

def set_follow_source
   puts 'before'
   yield
   puts 'after'
end

I have to clarify your question.我必须澄清你的问题。 Who or what component exactly should set this argument?谁或什么组件应该设置这个参数?

In case you want to create some DSL so as to set an argument beforehand for around action, you can do something like that:如果想创建一些 DSL 以便预先为周围操作设置参数,您可以执行以下操作:

def self.say_hello_to(name)
  lambda do |controller, block|
    hello name, &block
  end
end

around_action say_hello_to('smith'), only: :index

def index
end

private

def hello(name, &block)
  puts 'hello'
  yield
  puts name
end

Actually, it already accepts some arguments, you can access controller instance as argument in the action filter callback, like this:实际上,它已经接受了一些参数,您可以在操作过滤器回调中将控制器实例作为参数访问,如下所示:

around_action only: [:follow] do |controller, block|
  controller.send(:any_method); 
  block.call # or yield
end

looks like it's okay to do this kind of things in Rails, you can find similar example in Rails docs paragraph 8.2看起来在 Rails 中做这种事情是可以的,你可以在Rails 文档第 8.2 段中找到类似的例子

It is possible and here is an example from Rails code :这是可能的,这里是Rails 代码的一个例子:

 set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }

so you just need to pass the block to your around filter like that:所以你只需要像这样将块传递给你的周围过滤器:

around_action only: [:follow] do |_, blk|
 set_follow_source(@source, &blk)
end

def set_follow_source
   puts 'before'
   yield
   puts 'after'
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM