我有一个这样的辅助方法:
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方法。你能告诉我怎么做吗?
答案 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 merged从helper
控制台方法中删除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来检查更改。我希望它可以帮助您..