0

At this time I need to use three variables in three different methods with the respective file in the view, but I don't want to define each variable in each method.

How can I define the variable just once and have access to the variables from all the three methods?

Those are the methods:

def pendientes
end

def proceso
end

def finalizadas
end

Those are the three variables:

@pendientes     = Support.where("estado = ?", 1)
@procesos       = Support.where("estado = ?", 2)
@finalizadas    = Support.where("estado = ?", 3)

How do I need to define the variables to do it?

4
  • Why don't you want to define each variable in each method? Are you having refactoring problems? Commented Nov 29, 2013 at 18:21
  • Is just because I dont want to define it in each method, I think is better to do it with another way, with less code Commented Nov 29, 2013 at 18:31
  • Are these three methods in a controller? Commented Nov 29, 2013 at 18:56
  • Yes these are in the same controller Commented Nov 29, 2013 at 19:40

1 Answer 1

3

If you're working in the context of a controller, you could do something like this:

class MyController < ApplicationController
  before_filter :initialize_variables

  def pendientes
  end

  def proceso
  end

  def finalizadas
  end

  private

    def initialize_variables
      @pendientes = Support.where(estado: 1)
      @procesos = Support.where(estado: 2)
      @finalizadas = Support.where(estado: 3)
    end
end

Update:

If you roll with a before_filter, it may be a good idea to add only: [:pendientes, :proceso, :finalizadas] so that future actions added to the controller don't initialize the three variables.

Another option would be to delete the before_filter call and just invoke the initialize_variables method from each of the three existing actions.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think before_filter is the right case here. What if more actions to be added in this controller? You'll add unnecessary burdens to them. Then use :only to separate them?
:only would work. I don't think the extra database calls would add much burden if more actions got added, though. It may have been better to just call initialize_variables from each of the three actions that currently exist. I'll update my answer to mention the alternatives.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.