检测文件类型并调整图像大小

时间:2019-04-12 06:17:46

标签: ruby-on-rails ruby-on-rails-5 rails-activestorage

我有模型附件小工具支持pdf和图像。如何检测其图像,然后才调整其大小?当它是回形针时,一切都很简单。但现在 ? ;)

class Attachment < ActiveRecord::Base

        has_attached_file :attachment,
                styles:          lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"}  : {:thumb => { :geometry => "100x100#", :format => 'jpg'}, :medium => { :geometry => "300x300#", :format => 'jpg'}}},

        def is_image?
                attachment.instance.attachment_content_type =~ %r(image)
        end

end

如何使用主动存储进行类似上述的操作?我这样尝试:

class Attachment < ApplicationRecord
  has_one_attached :file
  validates :file, presence: true

def file_url
if ???? (is image?)
rails_blob_url(file.variant(resize: '1920x1920').processed)
else
rails_blob_url(file)
  end
end

2 个答案:

答案 0 :(得分:0)

ActiveStorage内置了用于流行内容类型的帮助器,例如:图像,视频,音频等。图像为image?

if file.image?
  rails_representation_url(file.variant(resize: '1920x1920').processed)
else
  rails_blob_url(file)
end

Api文档:https://api.rubyonrails.org/classes/ActiveStorage/Blob.html#method-i-image-3F

audio?, image?, text?, video?

答案 1 :(得分:0)

我已经尝试过了,..什么是“ signed_id”?


NoMethodError (undefined method `signed_id' for #<ActiveStorage::Variant:0x00007fb67a4325f0>):

activestorage (5.2.0) config/routes.rb:7:in `block (2 levels) in <main>'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:641:in `instance_exec'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:641:in `eval_block'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:630:in `call'
actionpack (5.2.0) lib/action_dispatch/routing/route_set.rb:164:in `block (2 levels) in add_url_helper'
app/models/attachment.rb:27:in `file_url'
app/serializers/api/v1/attachment_serializer.rb:7:in `file_url'