Module: Tiun::Migration

Included in:
Tiun
Defined in:
lib/tiun/migration.rb

Defined Under Namespace

Classes: Proxy

Constant Summary collapse

MigrationTemplate =
ERB.new(IO.read(File.join(File.dirname(__FILE__), "automigration.rb.erb")))
EMBED =
<<-END
   class ActiveRecord::MigrationContext
      alias :__old_migrations :migrations

      def migrations
         (Tiun.migrations | __old_migrations).sort_by(&:version)
      end
    end
END

Instance Method Summary collapse

Instance Method Details

#base_migrationObject



49
50
51
# File 'lib/tiun/migration.rb', line 49

def base_migration
   @base_migration ||= ActiveRecord::Migration[5.2]
end

#fields_for(type) ⇒ Object



57
58
59
# File 'lib/tiun/migration.rb', line 57

def fields_for type
   (type.fields || []) | (defaults.fields || [])
end

#migration_fields_for(type) ⇒ Object



61
62
63
64
65
66
# File 'lib/tiun/migration.rb', line 61

def migration_fields_for type
   fields_for(type).map do |attrs|
      type = detect_type(attrs.kind)
      type && { name: attrs.name, type: type, options: {} } || nil
   end.compact
end

#migration_name_for(type) ⇒ Object



53
54
55
# File 'lib/tiun/migration.rb', line 53

def migration_name_for type
   "Create" + type.name.pluralize.camelize
end

#migrationsObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/tiun/migration.rb', line 68

def migrations
   return @migrations if @migrations

   @migrations =
      types.reduce([]) do |migrations, type|
         next migrations if type.parent

         migration_name = migration_name_for(type)

         if migrations.any? { |m| m.name == migration_name }
            error :duplicated_migration_found, {name: migration_name, type: type}
         else
            table_title = table_title_for(type)
            migration_fields = migration_fields_for(type)
            code = MigrationTemplate.result(binding)
            timestamp = type.timestamp

            if timestamp
               migrations << Proxy.new(migration_name, type.timestamp, code)
            else
               error :no_timestamp_defined_for_migration, {name: migration_name, code: code}
            end
         end

         migrations
      end
end

#search_all_for(kind, value) ⇒ Object



96
97
98
# File 'lib/tiun/migration.rb', line 96

def search_all_for kind, value
   send(kind).select {|x| x.name == value }
end

#setup_migrationsObject



100
101
102
# File 'lib/tiun/migration.rb', line 100

def setup_migrations
   Kernel.module_eval(EMBED)
end