Sha256: 7fc8ace44a1aa9a5ecadfed65ff21515cbf4ee839ec6e4900364d4e842a0b6a5

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module ActiveRecord
  module SaferMigrations
    class SettingHelper
      def initialize(connection, setting_name, value)
        @connection = connection
        @setting_name = setting_name
        @value = value
      end

      # We're changing a connection level setting, and we need to make sure we return
      # it to the original value. It is automatically reverted if set within a
      # transaction which rolls back, so that case needs handling differently.
      #
      #                | In Transaction      | Not in transaction
      # ---------------------------------------------------------
      # Raises         | Reset setting       | Reset setting
      # Doesn't raise  | Don't reset setting | Reset setting
      def with_setting
        record_current_setting
        set_new_setting
        yield
        reset_setting
      rescue
        reset_setting unless in_transaction?
        raise
      end

      private

      def record_current_setting
        @original_value = @connection.get_setting(@setting_name)
      end

      def set_new_setting
        puts "-- set_setting(#{@setting_name.inspect}, #{@value})"
        @connection.set_setting(@setting_name, @value)
      end

      def reset_setting
        puts "-- set_setting(#{@setting_name.inspect}, #{@original_value})"
        @connection.set_setting(@setting_name, @original_value)
      end

      def in_transaction?
        ActiveRecord::Base.connection.open_transactions > 0
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
activerecord-safer_migrations-2.0.0 lib/active_record/safer_migrations/setting_helper.rb
activerecord-safer_migrations-1.0.0 lib/active_record/safer_migrations/setting_helper.rb
activerecord-safer_migrations-0.1.0 lib/active_record/safer_migrations/setting_helper.rb