在控制器内动态调用方法
我有以下场景,
我想向控制器动态添加方法。我所有的方法名称都在一个表中。请参考以下示例
-table (method_names)-
1 - Walk
2 - Speek
3 - Run
,我
class UsersController < ApplicationController
def index
end
end
在这个索引操作中有一个控制器,我想动态调用我的方法。这些方法实际上是在其他软件中实现的。
我有另一个像
class ActionImplementController < ApplicationController
def walk
puts "I'm walking"
end
def speek
puts "I'm sppeking"
end
def run
puts "I'm running"
end
end
** 这样的控制器,我做了类似下面的事情及其工作
class UsersController < ApplicationController
def index
a = eval("ActionImplementController.new.run")
end
end
,但我的问题是,这是正确的方法还是有其他方法可以做到这一点,
提前致谢,
欢呼
Sameera
I have the following scenario
I want to add methods dynamically to a controller. All my method names are in a table . Please refer the following example
-table (method_names)-
1 - Walk
2 - Speek
3 - Run
and I have a controller
class UsersController < ApplicationController
def index
end
end
Inside this index action i want to call my methods dynamically. Those methods were actually implemented else ware.
I have another controller like
class ActionImplementController < ApplicationController
def walk
puts "I'm walking"
end
def speek
puts "I'm sppeking"
end
def run
puts "I'm running"
end
end
** I have done something like below and its working
class UsersController < ApplicationController
def index
a = eval("ActionImplementController.new.run")
end
end
But my question is , is this the right way or is there anyother way to do this
Thanks in advance
cheers
sameera
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然第一个答案有效,但我更喜欢这样的东西
,然后在你的控制器中编写
更干净的代码,因为代码可以共享,但它是在你需要的地方定义的。
While the first answer works, i would prefer something like this
and then in your controller write
Much cleaner because the code can be shared, but it is defined where you need it.
我认为通常最好避免使用 eval。如果可以的话,我将使所有方法都成为类方法,然后像这样运行它们:
I think it's generally best to avoid the use of eval. If you can, I would make all your methods class methods and then run them like so: