Kyle Macey
Kyle Macey

Reputation: 8154

Extend an action in a controller

I'm building a controller that sets the same variables in several actions. Something like this:

def one
  @a = 1
  @b=2
  @test = "One"
end

def two
  @a = 1
  @b = 2
  @test = "Two"
end

I'm aware that I could call a method to fill in the variable assignments, but I'm wondering how one would do this the "Best Practice" way. I got ambitious and tried...

def master 
  @a = 1
  @b = 2
end

def one < master
  @test = "One"
end

def two < master
  @test = "Two"
end

But this arose to no avail. What does the SO community suggest?

Upvotes: 1

Views: 483

Answers (1)

rubyprince
rubyprince

Reputation: 17793

< is used for inheritance in Ruby and cannot be used on methods. In Rails you can call before_filter for this purpose.

before_filter :master

if you want it for all methods in the controller, or

before_filter :master, :only => [:one, :two]

if you want it for these methods only.

Upvotes: 4

Related Questions