1

I have a helper method like this:

module PostsHelper
  def foo
    "foo"
  end
end

And in rails console I check the function, then change the text "foo" to "bar", then reload! the console, but helpers.foo still doesn't return "bar".

Maybe Helper object is already created in the console like this post, I'm not sure about that. Rails Console: reload! not reflecting changes in model files? What could be possible reason?

Only I want to know is how to play with helper method in rails console. Could you show me how to do it?

Community
  • 1
  • 1
ironsand
  • 14,329
  • 17
  • 83
  • 176

2 Answers2

5

You are correct that helper represents an object that is already instantiated, and therefore not affected by calls to reload!. The helper method in the console is defined as:

def helper
  @helper ||= ApplicationController.helpers
end

The first time you call helper, it will memoize the ApplicationController helpers. When you call reload!, the ApplicationController class (and it's helpers) are reloaded, but the helper method is still looking at an old instance.

Instead of using the helper method, you can call ApplicationController.helpers directly, and you will see your changes after running reload!:

> helper.foo
# => "foo"
> ApplicationController.helpers.foo
# => "foo"
> # Change the return value of PostsHelper from "foo" to "bar"
> reload!
> helper.foo
# => "foo"
> ApplicationController.helpers.foo
# => "bar"

EDIT

Starting with Rails 5, this will no longer be an issue. A PR was merged to remove memoization from the helper console method.

Charles Treatman
  • 558
  • 3
  • 14
1

Suppose you have a helper module like the following:

module CarsHelper

  def put_a_car_in(location)
    if location == "your car"
      puts "So you can drive while you drive!"
    end
  end

end

Fire up a Rails console, and to create the helper-helper, all you have to do in include the module:

>> include CarsHelper # It is not necessary to include module
=> Object

>> helper.put_a_car_in("your car") # simply write helper.your_method_name
So you can drive while you drive!

reload! is not working I tried too. You have to quit from rails console and again have to start rails c to check changes..I hope it helps you..

Gagan Gami
  • 10,121
  • 1
  • 29
  • 55