如何使用Paperclip和Rails 3

时间:2015-05-18 15:11:37

标签: ruby-on-rails paperclip

我正在尝试使用基于此博客文章的回形针执行检查和调整图像大小的步骤:http://www.techdarkside.com/how-to-re-size-images-that-are-too-large-on-the-fly-with-paperclip-and-rails

这就是我所拥有的......

class Question < ActiveRecord::Base
  # subclasses
  class Question::Image < Asset
    has_attached_file :attachment,
                      :url => "/uploads/:class/:attachment/:id_partition/:basename_:style.:extension",
                      :styles => Proc.new { |attachment| attachment.instance.styles },
                      :styles => Proc.new { |attachment| attachment.instance.resize }
                        attr_accessible :attachment
    # http://www.ryanalynporter.com/2012/06/07/resizing-thumbnails-on-demand-with-paperclip-and-rails/
    def dynamic_style_format_symbol
        URI.escape(@dynamic_style_format).to_sym
      end

      def styles
        unless @dynamic_style_format.blank?
          { dynamic_style_format_symbol => @dynamic_style_format }
        else
          { :medium => "300x300>", :thumb => "100x100>" }
        end
      end

      def dynamic_attachment_url(format)
        @dynamic_style_format = format
        attachment.reprocess!(dynamic_style_format_symbol) unless attachment.exists?(dynamic_style_format_symbol)
        attachment.url(dynamic_style_format_symbol)
      end

      def resize
        if self.attachment_file_size > 2000000
          "300x300>"
        else
          " "
        end
      end
    end

我认为问题在于重用:styles符号,但是我不确定如何将styles方法和resize方法同时用于单个Proc语句。< / p>

1 个答案:

答案 0 :(得分:1)

感谢@janfoeh的建议,这是我最终的结果。我确实需要在样式选项中添加:original才能使其正常工作。我还将最大文件大小提高到5mb。

class Question < ActiveRecord::Base
  # subclasses
  class Question::Image < Asset
    has_attached_file :attachment,
                      :url => "/uploads/:class/:attachment/:id_partition/:basename_:style.:extension",
                      :styles => Proc.new { |attachment| attachment.instance.styles }
    attr_accessible :attachment

    # http://www.ryanalynporter.com/2012/06/07/resizing-thumbnails-on-demand-with-paperclip-and-rails/
    def dynamic_style_format_symbol
        URI.escape(@dynamic_style_format).to_sym
    end

    def styles
      unless @dynamic_style_format.blank?
        { dynamic_style_format_symbol => @dynamic_style_format }
      else
        { :original => resize, :medium => "300x300>", :thumb => "100x100>" }
      end
    end

    def dynamic_attachment_url(format)
      @dynamic_style_format = format
      attachment.reprocess!(dynamic_style_format_symbol) unless attachment.exists?(dynamic_style_format_symbol)
      attachment.url(dynamic_style_format_symbol)
    end

    def resize
      if self.attachment_file_size > 5000000
        "1000x1000>"
      else
        " "
      end
    end
  end