OSDN Git Service

v07
[pettanr/pettanr.git] / app / models / system_picture.rb
1 class SystemPicture < Peta::SystemResource
2   load_manifest
3   has_many :balloons
4   has_many :speech_balloon_templates
5   has_many :licenses
6   has_many :writing_formats
7   
8   validates :ext, :presence => true, :length => {:maximum => 4}, :inclusion => {:in => ['png', 'jpeg', 'gif']}
9   validates :width, :presence => true, :numericality => true, :natural_number => true
10   validates :height, :presence => true, :numericality => true, :natural_number => true
11   validates :filesize, :presence => true, :numericality => {:greater_than => 0, :less_than_or_equal_to => 2000000}, :natural_number => true
12   validates :md5, :presence => true, :length => {:minimum => 32, :maximum => 32}
13   
14   before_destroy :destroy_with_file
15   
16   scope :find_index, -> do
17     self
18   end
19   
20   def destroy_with_file
21     PictureIO.system_picture_io.delete self.filename
22   end
23   
24   def supply_default
25   end
26   
27   def overwrite
28   end
29   
30   def filename
31     "#{self.id}.#{self.ext}"
32   end
33   
34   def mime_type
35     "image/#{self.ext}"
36   end
37   
38   def url
39     '/system_pictures/' + filename
40   end
41   
42   def opt_img_tag
43     {:src => self.url, :width => self.width, :height => self.height}
44   end
45   
46   def tmb_opt_img_tag
47     tw, th = PettanImager.thumbnail_size(self.width, self.height)
48     {:src => self.url, :width => tw, :height => th}
49   end
50   
51   def symbol_option
52     self.tmb_opt_img_tag
53   end
54   
55   def self.show_opt
56     {}
57   end
58   
59   def store(imager)
60     unless imager
61       self.errors.add :base, 'illegal picture data'
62       return false
63     end
64     res = false
65     SystemPicture.transaction do
66       if res = self.save
67         begin
68           res = PictureIO.system_picture_io.put(imager.binary, self.filename)
69         rescue PictureIO::Error
70           res = false
71           self.errors.add :base, I18n.t('picture_io.error')
72           raise ActiveRecord::Rollback
73         end
74       end
75     end
76     res
77   end
78   
79   def self.store(imager)
80     attr = {:ext => imager.ext, :width => imager.width, :height => imager.height, :filesize => imager.filesize, :md5 => imager.md5}
81     sp = SystemPicture.modify_object(imager.md5, attr, 'md5')
82     res = sp.store imager
83     res ? sp : nil
84   end
85   
86   def restore(subdir = nil)
87     PictureIO.system_picture_io.get self.filename, subdir
88   end
89   
90 end