OSDN Git Service

pass model import test
[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 modify_object(name, attr, key = 'name')
20           c = 'find_by_' + key.to_s
21           r = self.__send__ c, name
22           if r
23             r.attributes = attr
24           else
25             r = self.new attr
26             r[key] = name if r[key].blank?
27           end
28           r
29         end
30         
31         def import_text(data, &blk)
32           d = JSON.parse_no_except(data)
33           return false unless d
34           res = []
35           self.transaction do
36             d.each do |name, item|
37               m = blk.call(name, item)
38               res.push(m) unless m.valid?
39             end
40             raise ActiveRecord::Rollback unless res.empty?
41           end
42           res
43         end
44         
45         def import_file(filename, &blk)
46           t = nil
47           begin
48             t = File.open(filename, 'r').read
49           rescue
50             return false
51           end
52           self.import_text t, &blk
53         end
54         
55       end
56       
57       module InstanceMethods
58         private
59         
60         public
61         
62       end
63       
64     end
65     include PettanImporter
66   end
67 end
68