bonekost bonekost - 1 month ago 13
Ruby Question

Spree 3.1: Increment Order number

I am trying to make Order number incremental in Spree 3.1.

I got only this:

Spree::Order.class_eval do
before_validation(on: :create) do
self.number = Spree::Core::NumberGenerator.new(prefix: 'S').send(:generate_permalink, Spree::Order)
end
end


but it's only change prefix.

How should I rewrite
new_candidate
to get right result?

#lib/spree/core/number_generator.rb
def new_candidate(length)
@prefix + length.times.map { @candidates.sample(random: @random) }.join
end

Answer

You can try this:

def new_candidate(host)
  max_number = host.maximum(:number) || STARTING_NUMBER
  @prefix + (max_number.gsub(@prefix, '').to_i + 1).to_s
end

def generate_permalink(host)
  new_candidate(host)
end

You will need to define STARTING_NUMBER constant in the generator class. Also, you will not need the @length instance variable anymore.