跳到内容 跳到搜索

Active Storage 变体

可应用于 Blob 以创建变体的转换集。此类通过 ActiveStorage::Blob#variant 方法公开,且很少直接使用。

如果您确实需要直接使用此方法,则使用转换哈希实例化它,其中键为命令,值为参数。示例

ActiveStorage::Variation.new(resize_to_limit: [100, 100], colourspace: "b-w", rotate: "-90", saver: { trim: true })

这些选项直接映射到 ImageProcessing 命令。

方法
C
D
E
F
K
N
T
W

属性

[R] transformations

类公共方法

decode(key)

返回一个 Variation 实例,其中包含由 encode 编码的转换。

# File activestorage/app/models/active_storage/variation.rb, line 35
def decode(key)
  new ActiveStorage.verifier.verify(key, purpose: :variation)
end

encode(transformations)

返回 transformations 的签名密钥,该密钥可用于在 URL 或组合密钥(如 ActiveStorage::Variant#key)中引用特定变体。

# File activestorage/app/models/active_storage/variation.rb, line 41
def encode(transformations)
  ActiveStorage.verifier.generate(transformations, purpose: :variation)
end

new(transformations)

# File activestorage/app/models/active_storage/variation.rb, line 46
def initialize(transformations)
  @transformations = transformations.deep_symbolize_keys
end

wrap(variator)

根据给定的 variator 返回一个 Variation 实例。如果 variator 是 Variation,则原样返回。如果它是一个 String,则将其传递给 ActiveStorage::Variation.decode。否则,假设它是一个转换 Hash,并直接传递给构造函数。

# File activestorage/app/models/active_storage/variation.rb, line 23
def wrap(variator)
  case variator
  when self
    variator
  when String
    decode variator
  else
    new variator
  end
end

实例公共方法

content_type()

# File activestorage/app/models/active_storage/variation.rb, line 70
def content_type
  Marcel::MimeType.for(extension: format.to_s)
end

default_to(defaults)

# File activestorage/app/models/active_storage/variation.rb, line 50
def default_to(defaults)
  self.class.new transformations.reverse_merge(defaults)
end

digest()

# File activestorage/app/models/active_storage/variation.rb, line 79
def digest
  OpenSSL::Digest::SHA1.base64digest Marshal.dump(transformations)
end

format()

# File activestorage/app/models/active_storage/variation.rb, line 62
def format
  transformations.fetch(:format, :png).tap do |format|
    if Marcel::Magic.by_extension(format.to_s).nil?
      raise ArgumentError, "Invalid variant format (#{format.inspect})"
    end
  end
end

key()

返回此变体实例化时使用的所有 transformations 的签名密钥。

# File activestorage/app/models/active_storage/variation.rb, line 75
def key
  self.class.encode(transformations)
end

transform(file, &block)

接受一个 File 对象,对其执行 transformations,并将转换后的图像保存到一个临时文件中。

# File activestorage/app/models/active_storage/variation.rb, line 56
def transform(file, &block)
  ActiveSupport::Notifications.instrument("transform.active_storage") do
    transformer.transform(file, format: format, &block)
  end
end