我正在尝试将图像保存到 Redis,稍后将在 Resque 任务中获取并上传到我们的图像服务器。
ImageHandle 类将为我们获取图像。目前,我只关心从 Redis 中获取图像。
class ImageHandle < ActiveRecord::Base
attr_accessible :uploaded, :image
after_save :save_image
def image_data
$redis.get(redis_key)
end
def image=(value)
@image = value
end
private
def redis_key
@redis_key ||= "image_handle:#{id}:image"
end
def save_image
$redis.set(redis_key, @image.read)
end
end
$redis 在初始化程序中设置的位置:
$redis = Redis.new
这是我的测试文件:
require 'test_helper'
class ImageHandleTest < ActiveSupport::TestCase
include ActionDispatch::TestProcess
setup do
clear_redis
end
test 'saves an image' do
image = fixture_file_upload('screaming-eagle.jpg', 'image/jpg')
# You can only read from a file fixture once
same_image = fixture_file_upload('screaming-eagle.jpg', 'image/jpg')
image_handle = ImageHandle.create(image: image)
expected = same_image.read
actual = image_handle.image_data
puts "length of expected: #{expected.length}"
puts "length of actual: #{actual.length}"
assert_equal expected, actual
end
end
结果是:
length of expected: 81500
length of actual: 78524
F
Finished tests in 0.270385s, 3.6984 tests/s, 3.6984 assertions/s.
1) Failure:
test_saves_an_image:23
我不知道是怎么回事。
当我尝试设置 ("b" * 81500) 然后获取它时,我将其恢复为预期的 81500 长度。
感谢你给与我的帮助。