1
votes

I am trying to access helper method in my controller using helpers like below:

  class MyController < ApplicationController
     def index
       @foo = 'bar'
       helpers.my_helper_method
     end
   end

Inside Helper method, I am trying to access an instance variable of controller

 module MyHelper
   def my_helper_method
    #some manipulation on foo
    @foo.to_i
   end
 end

But in above scenario @foo is nil. When I call the same method from view, @foo is available. So the instance variable can be passed to helper method only through UI or some other way is there?

Thanks in advance.

UPDATE:

view_context 

seems like reasonable solution https://apidock.com/rails/AbstractController/Rendering/view_context

2

2 Answers

1
votes
  class MyController < ApplicationController
     def index
       @foo = 'bar'
       helpers.my_helper_method(@foo)
     end
   end

 module MyHelper
   def my_helper_method(foo)
    #some manipulation on foo
    foo.to_i
   end
 end

pass it as argument.

-1
votes

You can access instance variables that you set in a controller in your helpers. If the value is nil, then you need to deal with it in your helper:

module SomeHelper
  def do_something
    return 0 if !@value
    value * 3
  end
end

class SomeController
  def index
    @value = 1
    helpers.do_something
  end

  def show
    @value = nil
    helpers.do_something
  end

end