gpt4 book ai didi

ruby-on-rails - 为 Paperclip Imagemagick 调整大小提供变量字符串模型

转载 作者:行者123 更新时间:2023-12-04 06:10:47 25 4
gpt4 key购买 nike

我正在使用回形针上传一些调整大小的图像。其中一种我想以五种方式之一进行裁剪......无论如何,我通过手动更改它们确定了要裁剪的字符串应该是什么样子,但现在我需要使其动态化,以便回形针可以基于裁剪用户想要什么...

问题是我得到了

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

我很确定这是因为我试图按照自己的意愿弯曲 rails 。无论如何,我认为我想要做的事情很清楚......只需将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

最佳答案

因此,当前的问题是您的模型无法访问请求参数(即 params[:crop_geometry] ),只能访问您的 Controller + View 。

在某些情况下(尽管这从来都不是一个好主意),您可以通过将 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] 分配“顶部”、“底部”或其他任何内容。

现在,要动态设置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 得到最后一部分(寻找“动态配置”)。

关于ruby-on-rails - 为 Paperclip Imagemagick 调整大小提供变量字符串模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com