6cb63e2304cb64236520d0e3e353c9bc

Coming from python, I would say this is pretty straight forward. But knowing some ruby, I suspect there's a DRYer way, right?

def before_create_save(record)
  vouchercode = generate_vouchercode(8)
  while Voucher.find(:first, :conditions => {:vouchercode => vouchercode})
    vouchercode = generate_vouchercode(8)
  end
  record.vouchercode = vouchercode
end

Refactorings

No refactoring yet !

A8d3f35baafdaea851914b17dae9e1fc

Adam

January 6, 2009, January 06, 2009 18:19, permalink

2 ratings. Login to rate!

Put those concerns in your model. Something like:

class Voucher < ActiveRecord::Base
  before_create :create_vouchercode
  
  protected
    def create_vouchercode
      self.vouchercode = generate_vouchercode(8)
      create_vouchercode if find_by_vouchercode(vouchercode)
    end
end
7f00244a6387413b37ee449f234ec045

Marc-Andre

January 13, 2009, January 13, 2009 01:49, permalink

1 rating. Login to rate!

...and if you favor using a while over recursion:

def create_vouchercode
  begin
    self.vouchercode = generate_vouchercode(8)
  end while find_by_vouchercode(vouchercode)
end
832ed6ace46d61032151f4e1864c057f

Dmitry Polushkin

January 22, 2009, January 22, 2009 10:06, permalink

1 rating. Login to rate!

What about magic number '8'?

6cb63e2304cb64236520d0e3e353c9bc

dive.myopenid.com

January 22, 2009, January 22, 2009 14:13, permalink

No rating. Login to rate!

nice nice nice thank you all! :-) uhm the magic 8 ... it's a variable to define the length of the vouchercode. but hm since it's always the 8 i coulda remove it ... good point!

Be1e3ee645d23c95ba650c21bc885927

Fabien Jakimowicz

February 12, 2009, February 12, 2009 13:34, permalink

No rating. Login to rate!

If you are using ActiveRecord and if your database supports it you should use unique indexes.

add_index(:vouchers, [:vouchercode], :unique => true)
class Voucher < ActiveRecord::Base
  def create_or_update
    super
  rescue ActiveRecord::StatementInvalid => e
    if e.to_s =~ %r{index_vouchers_on_vouchercode}i
      self.vouchercode = generate_vouchercode(8)
      retry
    else
      raise
    end
  end
end

Your refactoring





Format Copy from initial code

or Cancel