簡體   English   中英

Rails:如何通過控制器的before_action / after_action方法INLINE調用帶有ARGS的ApplicationController方法?

[英]Rails: How to call ApplicationController method WITH ARGS from a controller's before_action/after_action method INLINE?

我在應用程序控制器上有set_pagination_header ,我需要從其他一些控制器調用它:

# syntax error in line below
after_action :set_pagination_header, :my_argument_object, only: [:index]

def index
  @my_argument_object = Resource.page(1)
  render json: @my_argument_object
end

我可以直接發送原始的@my_argument_object所以我不想這樣做:

def set_pagination_header(name, options = {})
    scope = instance_variable_get("@#{name}")
    # some_logic_here
end

1)什么是正確的語法(需要內聯語法)?

2) 為什么不set_pagination_header(object, options = {})


編輯 :我在這里發現了一些東西

after_filter only: [:index] { set_pagination_header(:germs) }

這是舊的語法,我們現在獲得了after_action。 盡管如此,我相信有一種內聯的方法可以做到,不是嗎?

# I tried and that didn't work
after_action :set_pagination_header(:my_argument_object), only: [:index]
after_action { :set_pagination_header(:my_argument_object) } only: [:index]
after_action { :set_pagination_header, :my_argument_object } only: [:index]

您只需要向回調添加一個方法調用

after_action :set_pagination_header_callback, only: :index

def set_pagination_header_callback
  set_pagination_header(...your variables here...)
end

# application_controller.rb
def set_pagination_header(name, options = {})
  scope = instance_variable_get("@#{name}")
  # some_logic_here
end

內聯方式,但不是那么干凈!

after_action Proc.new{ set_pagination_header(:paged_orders) }, only: [:index]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM