OSDN Git Service

ccfe6af290b04f4153299efbec21f4cd44ed9618
[pettanr/pettanr.git] / app / models / system_picture.rb
1 class SystemPicture < ActiveRecord::Base
2   has_many :balloons
3   has_many :balloon_templates
4   has_many :licenses
5   
6   validates :ext, :presence => true, :length => {:maximum => 4}, :inclusion => {:in => ['png', 'jpeg', 'gif']}
7   validates :width, :presence => true, :numericality => true, :natural_number => true
8   validates :height, :presence => true, :numericality => true, :natural_number => true
9   validates :filesize, :presence => true, :numericality => {:greater_than => 0, :less_than_or_equal_to => 2000000}, :natural_number => true
10   validates :md5, :presence => true, :length => {:maximum => 32}
11   
12   before_destroy :destroy_with_file
13   
14   def destroy_with_file
15     PictureIO.system_picture_io.delete self.filename
16   end
17   
18   def dext
19     self.ext.downcase
20   end
21   
22   def filename
23     "#{self.id}.#{self.dext}"
24   end
25   
26   def mime_type
27     "image/#{self.dext}"
28   end
29   
30   def url
31     '/system_pictures/' + filename
32   end
33   
34   def data_to_mgk picture_data
35     begin
36       mgk = Magick::Image.from_blob(picture_data).shift
37     rescue 
38       self.errors.add :base, 'magick failed'
39       return false
40     end
41     mgk
42   end
43   
44   def store(picture_data)
45     mgk = data_to_mgk picture_data
46     return false unless mgk
47     res = false
48     self.attributes = {:ext => mgk.format.downcase, :width => mgk.columns, :height => mgk.rows, 
49       :filesize => mgk.filesize
50     }
51     self.md5 = Digest::MD5.hexdigest(picture_data)
52     SystemPicture.transaction do
53       if res = self.save
54         res = PictureIO.system_picture_io.put(picture_data, self.filename)
55       end
56     end
57     res
58   end
59   
60   def self.store(picture_data)
61     md5 = Digest::MD5.hexdigest(picture_data)
62     sp = SystemPicture.find_by_md5(md5)
63     sp = SystemPicture.new() unless sp
64     res = sp.store picture_data
65     res ? sp : nil
66   end
67   
68   def restore(subdir = nil)
69     PictureIO.system_picture_io.get self.filename, subdir
70   end
71   
72 end