OSDN Git Service

play panel_elements
[pettanr/pettanr.git] / app / models / panel.rb
1 class Panel < ActiveRecord::Base
2   belongs_to :comic
3   belongs_to :author
4   has_many :panel_pictures, :dependent => :destroy
5   has_many :balloons, :dependent => :destroy
6   accepts_nested_attributes_for :panel_pictures, :allow_destroy => true
7   accepts_nested_attributes_for :balloons, :allow_destroy => true
8
9   def self.max_t comic_id
10     Panel.maximum(:t, :conditions => ['comic_id = ?', comic_id]).to_i
11   end
12   
13   def self.find_t comic_id, t
14     Panel.find(:first, :conditions => ['comic_id = ? and t = ?', comic_id, t])
15   end
16
17   #更新する時にPanelIDをチェックしとかないと勝手に所属先を変えられるゾ!?
18
19   def vdt_save
20     f = nil
21     max_t = Panel.max_t self.comic_id
22     f = Panel.find_t(self.comic_id, self.t) if self.t
23     if f
24       Panel.update_all('t = t + 1', ['comic_id = ? and t >= ?', self.comic_id, self.t])
25     else
26       self.t = max_t + 1
27     end
28     self.save
29   end
30   
31   def move_to new_t
32     return true if self.t == new_t
33     if self.t > new_t
34       Panel.update_all('t = t + 1', ['comic_id = ? and (t >= ? and t < ?)', self.comic_id, new_t, self.t])
35     else
36       nf = Panel.find_t(self.comic_id, new_t)
37       max_t = Panel.max_t self.comic_id
38       new_t = max_t if new_t > max_t
39       Panel.update_all('t = t - 1', ['comic_id = ? and (t > ? and t <= ?)', self.comic_id, self.t, new_t])
40     end
41     self.t = new_t
42     self.save
43   end
44   
45   def destroy_and_shorten
46     Panel.update_all('t = t - 1', ['comic_id = ? and (t > ?)', self.comic_id, self.t])
47     self.destroy
48   end
49   
50   def own? author
51     return false unless author
52     self.author_id == author.id
53   end
54   
55   def sort_by_time
56     pe = []
57     self.panel_pictures.each do |picture|
58       pe[picture.t] = picture
59     end
60     self.balloons.each do |balloon|
61       pe[balloon.t] = balloon
62     end
63     pe
64   end
65   
66   def each_element
67     self.sort_by_time.each do |e|
68       yield e
69     end
70   end
71   
72   def panel_elements
73     res = []
74     self.each_element do |elm|
75       if elm.kind_of?(PanelPicture)
76         res[elm.t] = elm.to_json({:include => :resource_picture})
77       end
78       if elm.kind_of?(Balloon)
79         res[elm.t] = elm.to_json({:include => :speaches})
80       end
81     end
82     res
83   end
84   
85   def to_json_play
86     self.to_json :methods => :panel_elements
87   end
88 end