Rails 4 - 使用自定义回形针附件处理器解析参数的顺序
Rails 4 - order of param parsing with a custom paperclip attachment processor
我的内容 table 带有回形针图像附件以及一些用户选择的裁剪设置:
create_table "content", force: true do |t|
t.string "title"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.integer "crop_x"
t.integer "crop_y"
t.integer "crop_w"
t.integer "crop_h"
end
为了在服务器端处理用户指定的图像裁剪,我有一个自定义回形针处理器,我从 here:
module Paperclip
class CustomCropper < Thumbnail
def initialize(file, options = {}, attachment = nil)
super
@current_geometry.width = target.crop_w
@current_geometry.height = target.crop_h
end
def target
@attachment.instance
end
def transformation_command
crop_command = [
'-crop',
"#{target.crop_w}x" \
"#{target.crop_h}+" \
"#{target.crop_x}+" \
"#{target.crop_y}",
'+repage'
]
crop_command + super
end
end
end
我的问题是 crop_x,y,w,h 参数在 图像附件后被解析 ,因此自定义回形针处理器将所有字段视为 nil并且没有正确裁剪图像。
# rails processes the image_xxx params before the crop_xxx params
@content = Content.new(content_params)
是否有一种简洁的方法告诉 Rails 在附件图像之前处理裁剪边界字段? 或者是否有其他解决方案可以基本完成此操作?
我这辈子想不出 "clean" 方法。我最终做的是在使用附件调用 update/save 之前保存 crop_
值。
例如:
def update
if article_params[:image_crop_y].present?
@article.image_crop_y = article_params[:image_crop_y]
@article.image_crop_x = article_params[:image_crop_x]
@article.image_crop_w = article_params[:image_crop_w]
@article.image_crop_h = article_params[:image_crop_h]
@article.save
end
if @article.update(article_params)
...
end
end
就像我说的,不是 "cleanest" 方式,但对我来说很有效。
我的内容 table 带有回形针图像附件以及一些用户选择的裁剪设置:
create_table "content", force: true do |t|
t.string "title"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.integer "crop_x"
t.integer "crop_y"
t.integer "crop_w"
t.integer "crop_h"
end
为了在服务器端处理用户指定的图像裁剪,我有一个自定义回形针处理器,我从 here:
module Paperclip
class CustomCropper < Thumbnail
def initialize(file, options = {}, attachment = nil)
super
@current_geometry.width = target.crop_w
@current_geometry.height = target.crop_h
end
def target
@attachment.instance
end
def transformation_command
crop_command = [
'-crop',
"#{target.crop_w}x" \
"#{target.crop_h}+" \
"#{target.crop_x}+" \
"#{target.crop_y}",
'+repage'
]
crop_command + super
end
end
end
我的问题是 crop_x,y,w,h 参数在 图像附件后被解析 ,因此自定义回形针处理器将所有字段视为 nil并且没有正确裁剪图像。
# rails processes the image_xxx params before the crop_xxx params
@content = Content.new(content_params)
是否有一种简洁的方法告诉 Rails 在附件图像之前处理裁剪边界字段? 或者是否有其他解决方案可以基本完成此操作?
我这辈子想不出 "clean" 方法。我最终做的是在使用附件调用 update/save 之前保存 crop_
值。
例如:
def update
if article_params[:image_crop_y].present?
@article.image_crop_y = article_params[:image_crop_y]
@article.image_crop_x = article_params[:image_crop_x]
@article.image_crop_w = article_params[:image_crop_w]
@article.image_crop_h = article_params[:image_crop_h]
@article.save
end
if @article.update(article_params)
...
end
end
就像我说的,不是 "cleanest" 方式,但对我来说很有效。