【问题标题】:calling methods dynamically inside a controller在控制器内部动态调用方法
【发布时间】:2010-08-20 21:31:48
【问题描述】:

我有以下场景

我想向控制器动态添加方法。我所有的方法名称都在一个表中。请参考以下示例

-table (method_names)-

1 - Walk
2 - Speek
3 - Run

我有一个控制器

class UsersController < ApplicationController

   def index

   end 

end

在这个索引操作中,我想动态调用我的方法。这些方法实际上是在 else ware 中实现的。

我有另一个控制器,比如

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

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

提前致谢

干杯

同样的

【问题讨论】:

    标签: ruby-on-rails ruby methods eval


    【解决方案1】:

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

    module ImplementsActions
      def run
        ...
      end
    
      def walk
        ..
      end
    
      def ...
    end
    

    然后在你的控制器中写入

    class UsersController < ActionController::Base
    
      include ImplementsActions
    
      # now you can just use run/speek/walk
    
      def index
        run
      end
    end
    

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

    【讨论】:

      【解决方案2】:

      我认为通常最好避免使用 eval。如果可以的话,我会把你所有的方法都设为类方法,然后像这样运行它们:

      def index
          ActionImplementController.send :run
          # ActionImplementController.new.send(:run) works if you can't use class methods
      end
      

      【讨论】:

      • 您好,感谢您的快速回复-您能否解释一下如何为上述传递参数:run method sameera
      • 只需将它们添加到发送调用:Foo.send :method, arg1, arg2, ..., argN。另见ruby-doc.org/core/classes/Object.html#M000332
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      相关资源
      最近更新 更多