Permalink
Browse files

validate shop storage before photo upload, #388.

  • Loading branch information...
1 parent 8e48eb9 commit 9494ce2f7fffd045a17fb3d3df5b8eeac3ebc31a @saberma saberma committed Feb 1, 2012
Showing with 51 additions and 6 deletions.
  1. +2 −0 app/models/product.rb
  2. +14 −6 app/models/shop.rb
  3. +12 −0 app/validators/storage_validator.rb
  4. +22 −0 spec/models/photo_spec.rb
  5. +1 −0 spec/models/shop_spec.rb
View
@@ -208,6 +208,7 @@ class ProductOption < ActiveRecord::Base
class Photo < ActiveRecord::Base
belongs_to :product
+ delegate :shop, to: :product
default_scope order: 'position asc'
VERSION_KEYS = []
@@ -218,6 +219,7 @@ class Photo < ActiveRecord::Base
end
validates_size_of :product_image, maximum: 8000.kilobytes
+ validates_with StorageValidator
validates_property :mime_type, of: :product_image, in: %w(image/jpeg image/jpg image/png image/gif), message: "格式不正确"
View
@@ -42,6 +42,10 @@ class Shop < ActiveRecord::Base
before_create :init_valid_date, :init_currency
+ after_create do
+ FileUtils.mkdir_p self.path
+ end
+
before_update do
self.set_currency_format if currency_changed? # 修改币种,则更新相应格式(如果用户同时修改格式,则会被覆盖)
end
@@ -77,9 +81,17 @@ def plan_unlimited?
end
def storage # 已占用的容量(如要支持windows可修改为循环获取目录大小)
- Rails.cache.fetch("shop_storage_#{self.id}") do
+ #Rails.cache.fetch("shop_storage_#{self.id}") do
`du -sm #{self.path} | awk '{print $1}'`.to_i # 以M为单位
- end
+ #end
+ end
+
+ def available?
+ !self.deadline.past?
+ end
+
+ def storage_idle? # 存在剩余空间
+ (self.plan_type.storage - self.storage) > 0
end
end
@@ -106,10 +118,6 @@ def mobile_theme # 手机主题
end
- def available?
- !self.deadline.past?
- end
-
begin 'path'
def path # 商店相关的文件(主题)存放路径 /data/shops/1
@@ -0,0 +1,12 @@
+# encoding: utf-8
+class StorageValidator < ActiveModel::Validator #验证容量是否超过商店限制
+
+ # 需要限制的地方:
+ # 1. 图片上传
+ # 2. 主题上传
+ # 3. 附件上传
+ def validate(record)
+ record.errors[:base] << "商店容量已经用完,详情请进入[帐号]页面查看" unless record.shop.storage_idle?
+ end
+
+end
View
@@ -1,4 +1,26 @@
+# encoding: utf-8
require 'spec_helper'
describe Photo do
+
+ let(:shop) { Factory(:user).shop }
+
+ let(:iphone4) { Factory :iphone4, shop: shop }
+
+ context '#create' do
+
+ context 'shop storage is not idle' do # 容量已经用完
+
+ it "should be fail" do
+ photo = iphone4.photos.build
+ photo.product_image = Rails.root.join('spec/factories/data/products/iphone4.jpg')
+ photo.shop.stub!(:storage_idle?) { false }
+ photo.save
+ photo.errors.should_not be_empty
+ end
+
+ end
+
+ end
+
end
View
@@ -40,6 +40,7 @@
it 'should get storage' do # 已占用的容量
shop.themes.install theme
shop.storage.should eql 2
+ shop.storage_idle?.should be_true
end
end

0 comments on commit 9494ce2

Please sign in to comment.