Search code examples
ruby-on-railsbefore-filter

Pass return value of 'before_action' to coming actions


This is my 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

As you can see, each and every of the methods requires a new instance of MPD and saves it into my variable. Now, would it be possible to do that via before_action and after_action, provided by Rails?

I thought about something like:

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

It would require to get the return value from my before-filter and pass it then further to my after-filter.

Is this something that works? Thanks for your help.


Solution

  • This is done by assigning to controller instance variables.

    before_action :new_mpd
    
    def status
      # use @mpd
    end
    
    private
    
    def new_mpd
      @mpd = MPD.new
      @mpd.connect
    end