传递' before_action'的返回值即将到来的行动

时间:2015-09-28 12:21:45

标签: ruby-on-rails before-filter

这是我的MpdController:

class MpdController < ApplicationController
  require 'ruby-mpd'

  def status
    mpd = MPD.new
    mpd.connect
    # ... 
    mpd.disconnect
  end

  def help
    mpd = MPD.new
    mpd.connect
    # ... 
    mpd.disconnect
  end

  def pause
    mpd = MPD.new
    mpd.connect
    # ... 
    mpd.disconnect
  end
end

如您所见,每个方法都需要一个新的MPD实例并将其保存到我的变量中。 现在,是否可以通过Rails提供的before_action和after_action来做到这一点?

我想到了类似的东西:

before_action :new_mpd
after_action :disconnect_mpd

def new_mpd
    mpd = MPD.new
    mpd.connect
    mpd
end

def disconnect_mpd(mpd)
    mpd.disconnect
end

需要从我的前置过滤器获取返回值,然后将其传递给我的后置过滤器。

这是有效的吗? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

这是通过分配给控制器实例变量来完成的。

before_action :new_mpd

def status
  # use @mpd
end

private

def new_mpd
  @mpd = MPD.new
  @mpd.connect
end