简体   繁体   English

如何从String查找和使用辅助方法

[英]How to find and use a helper method from String

I would like to know how to find and use a helper method, when I have the name of the helper in a string format. 当我以字符串格式获取帮助器的名称时,我想知道如何查找和使用帮助器方法。

I am writing an engine, and in the initializer file, users can specify the current_user_helper as such: 我正在编写一个引擎,并且在初始化程序文件中,用户可以这样指定current_user_helper:

MyEngine.current_user_helper = "current_user"

I would like to do something with this in the controller. 我想在控制器中对此做些事情。 For instance, the code below tries to create a Post for the logged in user. 例如,下面的代码尝试为登录的用户创建一个帖子。

MyEngine.current_user_helper.posts.new(post_params)

Yet, this code does not work because MyEngine.current_user_helper is a string. 但是,由于MyEngine.current_user_helper是字符串,因此此代码不起作用。 Apparently, Rails will throw an error when I try: 显然,当我尝试时,Rails会抛出错误:

MyEngine.current_user_helper = current_user

without the quotation marks. 没有引号。

Any suggestions? 有什么建议么?

You can use send to call a method from a string or symbol. 您可以使用send从字符串或符号中调用方法。 send is available on all descendants of Object. send在Object的所有后代上可用。

send(MyEngine.current_user_helper).posts.new

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

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