gpt4 book ai didi

ruby-on-rails - 在 Controller 中动态调用方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:20 24 4
gpt4 key购买 nike

我有以下场景

我想向 Controller 动态添加方法。我所有的方法名称都在一个表中。请引用下面的例子

-table (method_names)-

1 - Walk
2 - Speek
3 - Run

我有一个 Controller

class UsersController < ApplicationController

def index

end

end

在此索引操作中,我想动态调用我的方法。这些方法实际上是在其他软件中实现的。

我有另一个 Controller

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

但我的问题是,这是正确的方法还是有其他方法可以做到这一点

提前致谢

干杯

萨米拉

最佳答案

虽然第一个答案有效,但我更喜欢这样的答案

module ImplementsActions
def run
...
end

def walk
..
end

def ...
end

然后在你的 Controller 中写入

class UsersController < ActionController::Base

include ImplementsActions

# now you can just use run/speek/walk

def index
run
end
end

更简洁,因为代码可以共享,但它是在您需要的地方定义的。

关于ruby-on-rails - 在 Controller 中动态调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3535030/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com