0

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)

Neil Middleton
  • 22,105
  • 18
  • 80
  • 134
  • are you dealing with lots of instance variables, if not simple return from your class and storing it in instance variable should be good to go – Ross Oct 15 '12 at 13:13
  • I don't want to return stuff as it limits what I can do with the class later on – Neil Middleton Oct 15 '12 at 13:14
  • How about you move your method - OtherClass.getStuff to a helper class so that it is accessible from view ? – royalghost Oct 15 '12 at 13:23
  • Helpers are primarily view helpers, not controller and I don't really want to dirty those waters. – Neil Middleton Oct 15 '12 at 13:24
  • You are confused. There is no such thing as "controller style code". A controller is just a class. You're asking to set an instance variable from the return value of a method in another class. See my answer. – Daniel Szmulewicz Oct 15 '12 at 13:46
  • 1
    Does OtherClass has to be a class? What if you change OtherClass to a module and mix in it into the controller? – Yanhao Oct 15 '12 at 14:38

2 Answers2

1
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.

ilan berci
  • 3,883
  • 1
  • 16
  • 21
0

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
Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191