Module: StuffArc::Base

Defined in:
lib/stuff_arc/stuff_arc.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



85
86
87
88
89
# File 'lib/stuff_arc/stuff_arc.rb', line 85

def self.included(mod)
  # if I'm included, then I want to extend myself
  puts "I'm being included in #{mod}!!!!"
  mod.send :extend, self
end

Instance Method Details

#archive(options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/stuff_arc/stuff_arc.rb', line 21

def archive options = {}
  return self.class.archive options unless self.class == Class
  mod_lowercase = self.to_s.underscore.pluralize
  
  unless (lib_dir = options.delete(:lib_dir))
    if Rails.public_path
      lib_dir =  File.join( File.dirname(::Rails.public_path), 'lib', 'stuff_arc' )
      Dir.mkdir(lib_dir) unless File.exists? lib_dir
    else
      lib_dir = '.'
    end
  end
  fname = options.delete(:fname) || "#{mod_lowercase}.json"
  fname = File.join(lib_dir, fname) unless fname[0] == File::SEPARATOR

  if File.exists? fname
    back_name = fname + '~'
    File.unlink back_name if File.exists? back_name
    File.rename fname, back_name
  end
  f = File.open(fname, 'w')
  list = self.all
  list.each do |instance|
    # as_json returns a hash, which we have to change to a JSON string
    f.write instance.as_json.to_json + "\n"
  end
  f.close
  list.length
end

#unarchive(options = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/stuff_arc/stuff_arc.rb', line 51

def unarchive options = {}
  return self.class.unarchive options unless self.class == Class
  mod_lowercase = self.to_s.underscore.pluralize

  unless (lib_dir = options.delete(:lib_dir))
    if Rails.public_path
      lib_dir =  File.join( File.dirname(::Rails.public_path), 'lib', 'stuff_arc' )
      Dir.mkdir(lib_dir) unless File.exists? lib_dir
    else
      lib_dir = '.'
    end
  end
  fname = options.delete(:fname) || "#{mod_lowercase}.json"
  fname = File.join(lib_dir, fname) unless fname[0] == File::SEPARATOR

  return nil unless File.exists? fname

  f = File.new fname

  counter = 0
  f.lines do |line|
    tmp = self.new.from_json(line.chomp)
    begin
      tmp.save!
      counter += 1
    rescue Exception => e
      puts "exception unarchiving #{self}: \#{e}\n"
    end
  end

  f.close
  counter
end