为Paperclip Imagemagick调整大小的模型提供变量字符串

时间:2011-10-19 00:45:12

标签: ruby-on-rails paperclip

我正在使用paperclip上传一些调整大小的图片。其中一个我想要被裁剪为五种方式中的一种......无论如何,我通过手工更改它们来确定要裁剪的字符串应该是什么样的,但现在我需要制作这种动态以便回形针可以裁剪为基础根据用户的需求......

问题在于我正在

undefined local variable or method `params' for #<Class:0x00000105b228d8>

我觉得很确定这是因为我试图按照我的意愿弯曲导轨。无论如何,我认为我很清楚我正在尝试做什么......只需将crop_geometry_thumb变量提供给convert_options ......我应该在哪里实际使用我的模型才能找到它的逻辑?

class Asset < ActiveRecord::Base
   if  params[:crop_geometry] == "bottom"
     crop_geometry_thumb = "-crop 200x100+0+100 -scale 100x100"
   elsif  params[:crop_geometry] == "top"
     crop_geometry_thumb = "-crop 200x100+0+0 -scale 100x100"
   elsif  params[:crop_geometry] == "left"
     crop_geometry_thumb = "-crop 100x200+0+100 -scale 100x100"
   elsif  params[:crop_geometry] == "right"
     crop_geometry_thumb = "-crop 100x200+100+0 -scale 100x100"
   else
     crop_geometry_thumb = "-scale 100x100"
   end

  belongs_to :piece
  has_attached_file :asset, :styles => {
    :large => ['700x700', :jpg], 
    :medium => ['300x300>', :jpg], 
    :thumb => ["200x200>", :jpg]},
    :convert_options => {:thumb => crop_geometry_thumb}, ### supply a string from above... FAIL :(
    :path => ":id/:style/:filename",
    :storage => :s3,
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
    :s3_permissions => :private,
    :url => ':s3_domain_url'
end

1 个答案:

答案 0 :(得分:3)

因此,直接的问题是您的模型无法访问请求参数(即params[:crop_geometry]),只能访问您的控制器+视图。

在某些情况下(虽然它从来都不是一个好主意),你可以通过将params作为方法的参数传递给你的模型来绕过这个MVC规则:

class FoosController < ApplicationController

  def action
     Foo.some_method(params)
  end
end

class Foo < ActiveRecord::Base

  some_method(params)
     puts params[:crop_geometry]
  end
end

相反,我建议将该参数信息传递给模型中定义的实例变量,并将条件逻辑放入自定义的setter方法中,如下所示:

class Asset < ActiveRecord::Base
  attr_reader :crop_geometry

  def crop_geometry=(crop_type)
    if  crop_type == "bottom"
     crop_string = "-crop 200x100+0+100 -scale 100x100"
    elsif  crop_type == "top"
      crop_geometry_thumb = "-crop 200x100+0+0 -scale 100x100"
    elsif  crop_type == "left"
      crop_geometry_thumb = "-crop 100x200+0+100 -scale 100x100"
    elsif  crop_type == "right"
      crop_geometry_thumb = "-crop 100x200+100+0 -scale 100x100"
    else
      crop_geometry_thumb = "-scale 100x100"
    end
    @crop_geometry = crop_geometry_thumb
  end
end

请注意,您必须更改表单,以便为params [:asset] [:crop_geometry]分配“top”,“bottom”或其他内容。

现在,要动态设置crop_geometry,您需要在has_attached_file配置中使用lambda - 这样每次访问配置时都会对其进行评估,而不仅仅是在最初加载模型时。你走了:

has_attached_file :asset, :styles => lambda {|attachment|
    :large => ['700x700', :jpg], 
    :medium => ['300x300>', :jpg], 
    :thumb => ["200x200>", :jpg]},
    :convert_options => {:thumb => attachment.instance.crop_geometry},
    :path => ":id/:style/:filename",
    ...
}

https://github.com/thoughtbot/paperclip得到最后一部分(寻找“动态配置”)。