OSDN Git Service

3418ec2771d97074d27158334692834eae93b382
[pettanr/pettanr.git] / vendor / plugins / pettan_importer / lib / pettan_importer.rb
1 #インポート処理
2 require 'common'
3
4 module ActiveRecord\r
5   class Base\r
6     module PettanImporter
7       def self.included(base)
8         base.extend(ClassMethods)
9         base.__send__ :include, InstanceMethods
10       end
11       
12       module ClassMethods
13         def each_import data
14           data.each do |n, d|
15             yield n, d
16           end
17         end
18         
19         def import(data, &blk)
20           d = JSON.parse_no_except(data)
21           return false unless d
22           res = []
23           self.transaction do
24             self.each_import(d) do |name, item|
25               m = blk.call(name, item)
26               res.push(m) unless m.valid?
27             end
28             raise ActiveRecord::Rollback unless res.empty?
29           end
30           res
31         end
32         
33         def import_file(filename)
34           t = nil
35           begin
36             t = File.open(filename, 'r').read
37           rescue
38             return false
39           end
40           self.import t
41         end
42         
43       end
44       
45       module InstanceMethods
46         private
47         
48         public
49         
50       end
51       
52     end
53     include PettanImporter
54   end
55 end
56