代码之家  ›  专栏  ›  技术社区  ›  sameera207

在控制器内动态调用方法

  •  2
  • sameera207  · 技术社区  · 14 年前

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

    -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
    

    但我的问题是,这是正确的方法还是有其他方法

    提前谢谢

    干杯

    2 回复  |  直到 14 年前
        1
  •  1
  •   cam    14 年前

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

    def index
        ActionImplementController.send :run
        # ActionImplementController.new.send(:run) works if you can't use class methods
    end
    
        2
  •  5
  •   nathanvda    14 年前

    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
    

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