Class: Unique::Generator
- Inherits:
-
Object
- Object
- Unique::Generator
- Defined in:
- lib/unique_id/generator.rb
Constant Summary collapse
- DEFAULT =
{ start: 1, scoped_by: nil, formatter: nil }
Instance Attribute Summary collapse
-
#attribute ⇒ Object
readonly
Returns the value of attribute attribute.
Instance Method Summary collapse
- #formatter ⇒ Object
-
#initialize(attribute, opts = {}) ⇒ Generator
constructor
A new instance of Generator.
- #next(opts) ⇒ Object
- #scope ⇒ Object
Constructor Details
Instance Attribute Details
#attribute ⇒ Object (readonly)
Returns the value of attribute attribute.
3 4 5 |
# File 'lib/unique_id/generator.rb', line 3 def attribute @attribute end |
Instance Method Details
#formatter ⇒ Object
20 21 22 |
# File 'lib/unique_id/generator.rb', line 20 def formatter @opts[:formatter] end |
#next(opts) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/unique_id/generator.rb', line 24 def next(opts) _scope = opts[:scope].nil? ? nil : opts[:scope].to_s _type = opts[:type] table = Arel::Table.new(:unique_ids) query = table .project( table[:value].maximum.as('v1') ) .where( table[:type].eq(_type).and(table[:scope].eq(_scope)) ) result = ActiveRecord::Base.connection.execute(query.to_sql).first max = result.is_a?(Hash) ? result['v1'] : result[0] next_value = max.nil? ? @opts[:start] : max.to_i + 1 ins_query = table.create_insert ins_query.into table ins_query.insert table[:type]=>_type, table[:scope]=>_scope, table[:value]=>next_value result = ActiveRecord::Base.connection.insert(ins_query, nil, nil, next_value) raise "Unexpected result: #{result}" unless result == next_value next_value end |
#scope ⇒ Object
16 17 18 |
# File 'lib/unique_id/generator.rb', line 16 def scope @opts[:scoped_by] end |