Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 92 lines (71 sloc) 1.992 kb
44a5031 @mislav devised a simple scheme for Mongo migrations
authored
1 require 'mingo'
2
3 class Mingo::Migration < Mingo
4 property :timestamp
5 property :name
6
7 attr_reader :description
8
9 def migrate(&block)
10 @migrate_operation = block
11 end
12
13 def migrate!
14 @migrate_operation.call(self)
15 self.save
16 end
17
18 def revert(&block)
19 @revert_operation = block
20 end
21
22 def revert!
23 @revert_operation.call(self)
24 # can't call `destroy` because it freezes
25 self.class.collection.remove('_id' => self.id)
26 self.delete('_id')
27 end
28
29 def describe(string)
30 @description = string.strip.tr("\n", ' ').gsub(/\s{2,}/, ' ')
31 end
32
33 alias_method :ran?, :persisted?
34
35 def pending?
36 !ran?
37 end
38
39 def ran_at
40 @ran_at ||= self.id && self.id.generation_time
41 end
42
43 def to_s
44 '[%s] %s: %s' % [timestamp, name, ran? ? 'performed' : 'pending']
45 end
46
47 def db
48 self.class.db
49 end
50
51 def self.migrations(dir)
52 load_migrations(migration_definitions(dir))
53 end
54
55 class << self
56 # used by `define` class method
57 attr_accessor :migration_filename, :last_defined_migration
58 end
59
60 def self.migration_definitions(dir)
61 Dir[File.join(dir, '**/*.rb')].select do |name|
62 File.basename(name) =~ /^\d+_/
63 end.sort
64 end
65
66 def self.load_migrations(files)
67 files.map { |file| load_migration file }
68 end
69
70 def self.load_migration(filename)
71 self.migration_filename = filename
72 Kernel.load filename
73 self.last_defined_migration
74 end
75
76 def self.define(&block)
77 raise ArgumentError unless self.migration_filename
78 timestamp, name = properties_from_filename(self.migration_filename)
79 migration = find_or_initialize(timestamp, name)
80 migration.instance_eval(&block)
81 self.last_defined_migration = migration
82 end
83
84 def self.find_or_initialize(timestamp, name)
85 first(:timestamp => timestamp) || new(:timestamp => timestamp, :name => name)
86 end
87
88 def self.properties_from_filename(name)
89 File.basename(name) =~ /^(\d+)_(.+)\.rb$/ and [$1.to_i, $2]
90 end
91 end
Something went wrong with that request. Please try again.