跳至内容 跳至搜索
方法
P
S

实例公共方法

param_encoding(action, param, encoding)

指定操作中参数的编码。如果未指定,则默认为 UTF-8。

你可以使用以下方式指定二进制 (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 77
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 48
def skip_parameter_encoding(action)
  @_parameter_encodings[action.to_s] = Hash.new { Encoding::ASCII_8BIT }
end