Rails控制器拆分def

时间:2014-05-05 22:41:16

标签: ruby-on-rails controller function

桌面应用程序向我的Rails应用程序发送请求,如

HTTP:/服务器/导入类型=目录&安培;模式= INIT

HTTP:/服务器/导入类型=目录&安培;模式=文件&安培;文件名=

HTTP:/服务器/导入类型=目录&安培;模式=进口&安培;文件名=

现在我的控制器看起来像

class ImportsController < ApplicationController
    include ImportsHelper
    skip_before_filter :verify_authenticity_token
  def index
    type = params[:type]
    mode = params[:mode]
    if type == "catalog"
        case mode
        when 'checkauth'
            generate_cookie
        render :text => "success\nimport_cookie\n#{set_cookie}\n"
      when 'init'
        render :text => "zip=yes\nfile_limit=52428800"
      when 'file' #uploadfile
                tempfile = Tempfile.new("importupload")
                tempfile.binmode
                tempfile << request.body.read
                tempfile.rewind
                import_params = params.slice(:filename, :type, :head).merge(:tempfile => tempfile)
            importf = ActionDispatch::Http::UploadedFile.new(import_params)
                @import = Import.new
                @import.filename = importf
                @import.cookie = cookie[:import_cookie]
                @import.save
        render :text => "success\n"
      when 'import'
        render :text => "232\n"
      else
        render :text => "wrong response\n"
      end
    else
        render :text => "wrong response\n"
    end

  end
end

如何将def拆分为控件看

class ImportsController < ApplicationController
    include ImportsHelper
    skip_before_filter :verify_authenticity_token
  def checkauth

  end

  def init

  end

  def file

  end

end

这可以使用routes.rb吗?

1 个答案:

答案 0 :(得分:1)

class ImportsController < ApplicationController
  include ImportsHelper
  skip_before_filter :verify_authenticity_token

  def index
    if %w(checkauth file init import).include? params[:mode]
      send(params[:mode])
    else
      render :text => "wrong response\n"
    end
  end

  private 

  def checkauth
    ...
  end

  def import 
    ...
  end 

  def init
    ...
  end

  def file
    ...
  end
end