Sha256: 0ce5fbf525d51461157bf7d4b38d54f63fb4d81034a7e15bb6552d80300d546d

Contents?: true

Size: 1.54 KB

Versions: 4

Compression:

Stored size: 1.54 KB

Contents

require 'hanami/commands/generate/abstract'

module Hanami
  module Commands
    class Generate
      class Migration < Abstract

        attr_reader :name, :underscored_name

        # @since 0.6.0
        # @api private
        #
        # @example
        #   20150612160502
        TIMESTAMP_FORMAT = '%Y%m%d%H%M%S'.freeze

        # @since 0.6.0
        # @api private
        #
        # @example
        #   20150612160502_create_books.rb
        FILENAME_PATTERN = '%{timestamp}_%{name}.rb'.freeze

        def initialize(options, name)
          super(options)

          @name = name
          @underscored_name = Utils::String.new(@name).underscore

          environment.require_application_environment
          assert_migration_name!
        end

        def map_templates
          add_mapping('migration.rb.tt', destination_path)
        end

        private

        def destination_path
          existing_migration_path || new_migration_path
        end

        def existing_migration_path
          Dir.glob("#{Hanami::Model.configuration.migrations}/[0-9]*_#{underscored_name}.rb").first
        end

        def new_migration_path
          timestamp = Time.now.utc.strftime(TIMESTAMP_FORMAT)
          filename = FILENAME_PATTERN % { timestamp: timestamp, name: underscored_name}

          Hanami::Model.configuration.migrations.join(filename)
        end

        def assert_migration_name!
          if name.nil? || name.strip.empty?
            raise ArgumentError.new('Migration name nil or empty')
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
hanami-0.7.3 lib/hanami/commands/generate/migration.rb
hanami-0.7.2 lib/hanami/commands/generate/migration.rb
hanami-0.7.1 lib/hanami/commands/generate/migration.rb
hanami-0.7.0 lib/hanami/commands/generate/migration.rb