Sqlserver::Sequence
A Rails plugin for SQL Server sequences.
Installation
Add this line to your application's Gemfile:
gem 'sqlserver-sequence'And then execute:
$ bundle
Or install it yourself as:
$ gem install sqlserver-sequence
Usage
Specify the attribute you'd like to sequence
class Supplier < ActiveRecord::Base
  sequence :number
endNow when you create a record number will be assigned the next value for that sequence.
$ supplier = Supplier.create
$ supplier.number
> 10 # generated by sequence named 'number'
$ other_supplier = Supplier.create
$ other_supplier.number
> 11
You can also define multiple sequences
class Supplier < ActiveRecord::Base
  sequence :number
  sequence :purchase_order
endOptions
name
By default sqlserver-sequence will look for a row in sys.sequences with the same sequence_name as the attribute. You can use the name option if the sequence is named differently.
class Supplier < ActiveRecord::Base
  sequence :number, name: 'next_supplier_number'
end$ supplier = Supplier.create
$ supplier.number 
> 10 # generated by sequence named 'next_supplier_number'
prefix
You can use the prefix option to prepend every sequence value with a string.
class Supplier < ActiveRecord::Base
  sequence :number, prefix: 'S-'
end$ supplier = Supplier.create
$ supplier.number
> S-10
format
Pass a lambda to the format option if you need more control over the assigned sequence value, for example to assign a fixed length string.
class Supplier < ActiveRecord::Base
  sequence :number, prefix: 'S-',
                    format: lambda { |num| num.rjust(10, 0) }
end$ supplier = Supplier.create
$ supplier.number
> S-0000000010
Configuration
Override any of these defaults in config/initializers/sqlserver_sequence.rb:
Sqlserver::Sequence.configure do |config|
  config.next_value_strategy = Sqlserver::Sequence::Strategies::NextValueFor
endnext_value_strategy
By default Sqlserver::Sequence will use a strategy that implements SQL Server's NEXT VALUE FOR function.
To change how sequences are generated you can also assign your own strategy:
# lib/size_strategy.rb
module SizeStrategy
  def next_sequence_value(sequence_name)
    self.class.size
  end
end
# config/initializers/sqlserver_sequence.rb
Sqlserver::Sequence.configure do |config|
  config.next_value_strategy = SizeStrategy
endDevelopment and Testing without SQL Server
If your test or development environment uses something other than SQL Server (e.g. SQLite) a Simple strategy is provided to avoid errors.
Sqlserver::Sequence.configure do |config|
  config.next_value_strategy = Sqlserver::Sequence::Strategies::Simple
endContributing
- Fork it ( https://github.com/zacharywelch/sqlserver-sequence/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
See the Running Tests guide for details on how to run the test suite on SQL Server.