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

RubyonRails中的控制器有部分功能吗

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

    我有一个控制器有1000多行代码。

    对不对,我正在为这个控制器做代码审查。 我根据模块安排我的方法。 现在我意识到我的控制器不容易维护,所以我想如下

    class UsersController < ApplicationController  
      #Code to require files here 
      #before filter code will goes here 
    
      #############Here i want to call that partial like things. following is just pseudo #########
        history module
        account module
        calendar module
        shipment module
        payment module
     ####################################################################
    
    end #end of class
    

    这有助于我维护代码,因为当我更改历史模块时,我确信我的帐户模块是不变的。我知道cvs,但我更喜欢每个模块的50个副本,而不是我的用户的controller.rb本身的200个副本。

    P.S.:-我想要肯定的答案。请不要这样回答,您应该为不同的模块使用不同的控制器…..bla…bla…bla…因为我不可能这样做。

    编辑:-我的版本是

    rails -v
      Rails 2.3.4
    ruby -v
      ruby 1.8.6 (2008-08-11 patchlevel 287) [i386-linux]
    
    3 回复  |  直到 14 年前
        1
  •  5
  •   Chris    14 年前

    这应该对你有用:

    app/controllers/some_controller.rb

    class SomeController < ApplicationController
      include MyCustomMethods
    end
    

    lib/my_custom_methods.rb

    module MyCustomMethods
      def custom
        render :text => "Rendered from a method included from a module!"
      end
    end
    

    config/routes.rb

    # For rails 3:
    match '/cool' => "some#custom"
    
    # For rails 2:
    map.cool 'cool', :controller => "some", :action => "custom"
    

    启动应用程序并点击 http://localhost:3000/cool ,您将从模块中获得您的自定义方法。

        2
  •  1
  •   Jed Schneider    14 年前

    假设您使用的是伪代码,您所指的是Ruby模块,而不是其他模块,那么只需将您的所有需求/模块放在一个单独的模块中,并包含这些模块,或者让您的用户控制器在重用这些文件时从基类继承。在第一种情况下,您可以将模块视为一个混合模块,它是为您想要的模块性而设计的。

    module AllMyStuff
      include History
      include Account
      ...
    end
    
    class UsersController < ApplicationController
      include AllMyStuff
    
      def new
      end
      ...
    end
    

    或者您可以从基本控制器继承,在这种情况下,这可能是一个合理的解决方案。

    def BaseController < ActionController
      include history
      include account
    end
    
    def UsersController < BaseController
      # modules available to this controller by inheritance
      def new
      end
      ...
    end
    
        3
  •  0
  •   Meduza    14 年前

    我尝试了以下方法,我已经运行了,也许它适合您:

    应用程序/用户控制器.rb

    require 'index.rb'
    class UsersController < ApplicationController  
      # some other code
    end
    

    应用程序/索引

    class UsersController < ApplicationController
    
    def index
      @users = User.all
    end
    
    end
    

    我的环境:Rails 3 Beta4