简体   繁体   English

如何在常规Ruby类中包含rails ApplicationHelper模块

[英]How to include rails ApplicationHelper module in a regular Ruby Class

I have a class in my Rails app's lib directory and I want to be able to use the helpers I created in ApplicationHelper from inside that class. 我在Rails应用程序的lib目录中有一个类,并且我希望能够使用从该类内部在ApplicationHelper中创建的帮助器。 I have the following: 我有以下几点:

module ApplicationHelper

  def works
    "Yay!"
  end   

  def breaks
    session[:username]
  end
end

class MyClass
  include ApplicationHelper
end

The following works 以下作品

MyClass.new.works 

This breaks 这打破了

MyClass.new.breaks

I get a message about Rails trying to delegate session to controller.session , but it can't do it because controller is nil. 我得到一个消息Rails的尝试委派sessioncontroller.session ,而是因为它不能做到这一点controller是零。

What's the right way to include ApplicationHelper? 包含ApplicationHelper的正确方法是什么?

The issue is not with including the helper, but with accessing the session. 问题不在于包括帮助程序,而在于访问会话。

In the normal scenario, the ApplicationHelper is automatically included in all controllers, and some of the ActionView methods - including session - are delegated to the controller which is present in this case. 在正常情况下, ApplicationHelper会自动包含在所有控制器中,并且某些ActionView方法(包括session )会委派给这种情况下存在的控制器

When included in a regular ruby class, there is no controller ; 当包含在常规的红宝石类中时,没有controller so any call to these methods will throw an error saying the controller is nil. 因此,对这些方法的任何调用都会引发错误,指出控制器为nil。

Not sure why you would need session information in a regular ruby class. 不确定为什么在常规的ruby类中需要会话信息。

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

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