OSDN Git Service

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