Rails 3: Call functions inside controllers

前端 未结 4 549
误落风尘
误落风尘 2020-12-29 11:31

If I want to have functions to be called inside controllers, where should I put them?

相关标签:
4条回答
  • class YourController < ActionController::Base
    
      def your_action
        your_function
      end
    
      private
    
        def your_function
    
        end
    end
    

    Also look at before_filter and after_filter, they're often useful in such kind of things

    0 讨论(0)
  • 2020-12-29 11:45

    if you want it to be local to a controller then all you need to do is to add it to the controller you wish to use.

    private
    def myfunction
      function code.....
    end
    

    to all controllers you can put it inside the application controller, because all controlers are sub classed.

    ApplicationController

    protected
    
    def myfunction
    
      function code.....
    
    end
    

    If you want access in your views then you can create a helper

    ApplicationHelper

    def myfunction
    
      function code...
    
    end
    
    0 讨论(0)
  • 2020-12-29 11:48

    The ApplicationController is here for that, since every Controller inherited from it.

    0 讨论(0)
  • 2020-12-29 11:50

    @jonnii, for example, I want to call a function that returns a generated unique code.

    If your generated code is going to be used only on your controllers, put the function inside a controller, as protected function (the easiest way would be putting it inside ApplicationController).

    If you need to call the function on the views, then put it on a helper, like ddayan says.

    If you also need to invoke the function from models, then the simplest way to do it is by putting a module inside the /lib/ directory.

    # /lib/my_module.rb
    module MyModule
      def generate_code
        1
      end
    end
    

    You will also need to include it with an initializer:

    #/config/initializers/my_module.rb
    require 'my_module'
    

    From that moment on, you can use the function like this:

    MyModule::generate_code
    

    If you are doing this very often, consider creating a gem.

    0 讨论(0)
提交回复
热议问题