Neil Middleton
Neil Middleton

Reputation: 22238

Extending a controller in Rails

I have a controller which calls out to another class.

class BlahController < ActionController
  def index
    OtherClass.get_stuff
  end
end

In this class I want to be able to write controller style code.

for instance:

class OtherClass
  def self.get_stuff
    @foo = bar
  end
end

However, I would also like @foo to exist when inside my view, but as it's a separate class those variables aren't making it back through into the controller assigns - so question is, how I can make this so?

(Ignore why I'm having to call out to a separate class, I'm trying to get this code fitting in with a legacy codebase without too much butchery)

Upvotes: 0

Views: 413

Answers (2)

Wayne Conrad
Wayne Conrad

Reputation: 107969

Code structured like this will be difficult to read and maintain. Whenever you can, let the controller directly set all of the variables that the view needs:

class BlahController < ActionController
  def index
    @foo = OtherClass.get_stuff
  end
end

class OtherClass
  def self.get_stuff
    # return the value that should be assigned to @foo  
  end
end

Upvotes: 0

ilan berci
ilan berci

Reputation: 3881

class BlahController < ActionController
  def index
    OtherClass.get_stuff(self)
  end
end

class OtherClass
  def self.get_stuff(that)
    that.instance_variable_set(:@foo, bar)
  end
end

Please note that I don't agree with this method. I am just answering the question as you stated it.

I would prefer to accomplish this functionality through mixins and thereby decrease parameter coupling that is present within the code above.

Upvotes: 1

Related Questions