简体   繁体   English

Helper方法不会在Rails控制台中通过`reload!`重新加载

[英]Helper method doesn't reload by `reload!` in rails console

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! 然后在Rails控制台中检查该功能,然后将文本"foo"更改为"bar" ,然后reload! the console, but helpers.foo still doesn't return "bar" . 控制台,但是helpers.foo仍然不返回"bar"

Maybe Helper object is already created in the console like this post, I'm not sure about that. 也许像这样的帖子已经在控制台中创建了Helper对象,但我不确定。 Rails Console: reload! Rails控制台:重新加载! 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. 我唯一想知道的是如何在Rails控制台中使用辅助方法。 Could you show me how to do it? 你能告诉我怎么做吗?

You are correct that helper represents an object that is already instantiated, and therefore not affected by calls to reload! 您是正确的, helper代表一个已实例化的对象,因此不受reload!调用的影响reload! . The helper method in the console is defined as: 控制台中的helper方法定义为:

def helper
  @helper ||= ApplicationController.helpers
end

The first time you call helper , it will memoize the ApplicationController helpers. 第一次调用helper ,它将记住ApplicationController帮助器。 When you call reload! 当您致电reload! , the ApplicationController class (and it's helpers) are reloaded, but the helper method is still looking at an old instance. ,将重新加载ApplicationController类(及其助手),但helper方法仍在查看旧实例。

Instead of using the helper method, you can call ApplicationController.helpers directly, and you will see your changes after running reload! 您可以直接调用ApplicationController.helpers ,而无需使用helper方法,并且在运行reload!之后将看到所做的更改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. 从Rails 5开始,这将不再是一个问题。 A PR was merged to remove memoization from the helper console method. PR已合并以从helper控制台方法中删除便笺。

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: 启动一个Rails控制台,并创建helper-helper,您所要做的全部工作包括以下模块:

>> 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.. 您必须quit rails console ,再次必须启动rails c来检查更改。希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM