OSDN Git Service

afa4198a7e72b7a5a88704d600536c39aabba429
[pettanr/pettanr.git] / app / models / writing_format.rb
1 class WritingFormat < ActiveRecord::Base
2   has_many :speeches
3   belongs_to :system_picture
4   
5   validates :name, :presence => true, :uniqueness => true, :length => {:maximum => 50}
6   validates :classname, :presence => true, :length => {:maximum => 50}
7   validates :caption, :presence => true, :length => {:maximum => 30}
8   validates :t, :presence => true, :numericality => {:greater_than_or_equal_to => 0}
9   validates :system_picture_id, :presence => true, :numericality => true, :existence => {:both => false}
10   validates :settings, :presence => true
11   
12   before_validation :valid_encode
13   
14   def valid_encode
15     ['name', 'classname', 'caption', 'settings'].each do |a|
16       next if attributes[a] == nil
17       raise Pettanr::BadRequest unless attributes[a].valid_encoding?
18     end
19   end
20   
21   def supply_default
22   end
23   
24   def overwrite
25     self.t = WritingFormat.count.to_i if self.new_record?
26   end
27   
28   def visible? author
29     true
30   end
31   
32   def self.list
33     opt = {}
34     opt.merge!(self.list_opt)
35     opt.merge!({:order => 'writing_formats.t asc'})
36     WritingFormat.find(:all, opt)
37   end
38   
39   def self.list_opt
40     {}
41   end
42   
43   def self.list_json_opt
44     {}
45   end
46   
47   def self.show rid, au
48     opt = {}
49     opt.merge!(self.show_opt)
50     res = WritingFormat.find(rid, opt)
51     raise ActiveRecord::Forbidden unless res.visible?(au)
52     res
53   end
54   
55   def self.show_opt
56     {}
57   end
58   
59   def self.show_json_opt
60     {}
61   end
62   
63   def self.store name, attr
64     r = WritingFormat.replace_system_picture(attr || {})
65     attr["settings"] = r["settings"] ? r["settings"].to_json : nil
66     r = WritingFormat.modify_object name, attr
67     r.overwrite
68     r.save
69     r
70   end
71   
72   def parsed_settings
73     @parsed_settings ||= JSON.parse(self.settings)
74   end
75   
76   def engine_name
77     Pettanr::Application.writing_formats[self.classname]
78   end
79   
80   def engine_module_name
81     self.engine_name.camelize
82   end
83   
84   def engine
85     Object.const_get self.engine_module_name
86   end
87   
88   def engine_model
89     engine.const_get 'Renderer'
90   end
91   
92   def self.import filename
93     WritingFormat.import_file(filename) {|name, attr| WritingFormat.store(name, attr)}
94   end
95   
96   def self.disp_import_error r
97     if r == false
98       puts "json file error. file does not exist or broken"
99     else
100       unless r.empty?
101         r.each do |sbt|
102           put sbt.errors.full_messages
103         end
104       end
105     end
106   end
107 end