跳至內容 跳至搜尋
方法
P
S

執行個體公開方法

param_encoding(action, param, encoding)

指定動作上一個參數的編碼。若未指定,預設為 UTF-8。

您可透過以下方式指定一個 2 進位(ASCII_8BIT)參數:

class RepositoryController < ActionController::Base
  # This specifies that file_path is not UTF-8 and is instead ASCII_8BIT
  param_encoding :show, :file_path, Encoding::ASCII_8BIT

  def show
    @repo = Repository.find_by_filesystem_path params[:file_path]

    # params[:repo_name] remains UTF-8 encoded
    @repo_name = params[:repo_name]
  end

  def index
    @repositories = Repository.all
  end
end

show 動作上的 file_path 參數將編碼為 ASCII-8BIT,但所有其他參數仍編碼為 UTF-8。這適用於應用程式必須處理資料,但資料編碼未知的情況,例如檔案系統資料。

# File actionpack/lib/action_controller/metal/parameter_encoding.rb, line 79
def param_encoding(action, param, encoding)
  @_parameter_encodings[action.to_s][param.to_s] = encoding
end

skip_parameter_encoding(action)

指定特定動作的所有參數應全部編碼為 ASCII-8BIT(它會「略過」UTF-8 的編碼預設值)。

例如,控制器會像這樣使用它

class RepositoryController < ActionController::Base
  skip_parameter_encoding :show

  def show
    @repo = Repository.find_by_filesystem_path params[:file_path]

    # `repo_name` is guaranteed to be UTF-8, but was ASCII-8BIT, so
    # tag it as such
    @repo_name = params[:repo_name].force_encoding 'UTF-8'
  end

  def index
    @repositories = Repository.all
  end
end

上述控制器中的 show 動作會有所有參數值編碼為 ASCII-8BIT。這適用於應用程式必須處理資料,但資料編碼未知的情況,例如檔案系統資料。

# File actionpack/lib/action_controller/metal/parameter_encoding.rb, line 50
def skip_parameter_encoding(action)
  @_parameter_encodings[action.to_s] = Hash.new { Encoding::ASCII_8BIT }
end