Ruby on Rails中的控制器是否有任何部分内容

时间:2010-07-17 08:20:01

标签: ruby-on-rails ruby partial controllers

我的控制器有超过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个副本而不是200个我的users_controller.rb本身。 / p>

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 个答案:

答案 0 :(得分:5)

这应该适合你:

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,您将从模块中获得自定义方法。

答案 1 :(得分:1)

假设您使用伪代码表示您指的是Ruby模块,而不是其他东西,只需将所有需求/模块放在一个单独的模块中并包含该模块,或者如果您正在重用这些文件,请让您的UsersController从基类继承。在第一种情况下,您可以将模块视为混合模式,它的设计完全符合您想要的模块化。

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

答案 2 :(得分:0)

我尝试了以下方法,并让它运行,也许它适合你:

应用程序/ user_controller.rb

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

应用程序/ index.rb

class UsersController < ApplicationController

def index
  @users = User.all
end

end

MY ENV:rails 3 beta4