Helper方法不会通过rails控制台中的“reload!”重新加载

时间:2014-10-14 06:46:31

标签: ruby-on-rails helper rails-console

我有一个这样的辅助方法:

module PostsHelper
  def foo
    "foo"
  end
end

在rails控制台中,我检查了该功能,然后将文本"foo"更改为"bar",然后将reload!更改为控制台,但helpers.foo仍未返回{{ 1}}。

也许已经在控制台中创建了Helper对象,就像这篇文章一样,我不确定。 Rails Console: reload! not reflecting changes in model files? What could be possible reason?

只有我想知道如何在rails控制台中使用helper方法。你能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:4)

您是正确的helper表示已经实例化的对象,因此不会受到reload!的调用的影响。控制台中的helper方法定义为:

def helper
  @helper ||= ApplicationController.helpers
end

第一次拨打helper时,它会记住ApplicationController个助手。当您调用reload!时,会重新加载ApplicationController类(及其帮助程序),但helper方法仍在查看旧实例。

您可以直接致电helper,而不是使用ApplicationController.helpers方法,在运行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"

修改

从Rails 5开始,这将不再是一个问题。 PR was mergedhelper控制台方法中删除memoization。

答案 1 :(得分:1)

假设您有一个如下所示的辅助模块:

module CarsHelper

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

end

启动Rails控制台,并创建帮助程序助手,您只需要包含该模块:

>> 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!无法正常工作我也试过了。您必须quit来自rails console并再次启动rails c来检查更改。我希望它可以帮助您..