Sha256: 28b4df3d1b8017b5b766d0fb9275312c44f9d0a68cb3382dced7585a1a5d5fa5

Contents?: true

Size: 1.18 KB

Versions: 2

Compression:

Stored size: 1.18 KB

Contents

require 'active_support/concern'
require 'sqlserver/sequence/version'

module Sqlserver
  module Sequence
    extend ActiveSupport::Concern

    class_methods do
      def sequence(field, options = {})
        unless defined?(sequences)
          include Sqlserver::Sequence::InstanceMethods
    
          class_attribute :sequences
          self.sequences = {}
    
          before_create :set_sequences
        end

        default_options = { name: field.to_s, format: nil, prefix: nil }
        self.sequences[field] = default_options.merge(options)
      end
    end

    module InstanceMethods
      
      def next_sequence_value(sequence_name)
        self.class.connection.select_value(
          "select next value for #{sequence_name}"
        )
      end

      private

      def set_sequences
        sequences.each do |field, options|
          name = options[:name]
          prefix = options[:prefix]
          format = options[:format]

          value = next_sequence_value(name)
          value = format.call(value) if format.respond_to?(:call)
          send "#{field}=", [prefix, value].join
        end
      end
    end
  end
end

ActiveRecord::Base.send :include, Sqlserver::Sequence

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sqlserver-sequence-0.1.1 lib/sqlserver/sequence.rb
sqlserver-sequence-0.0.1 lib/sqlserver/sequence.rb