Skip to content

Instantly share code, notes, and snippets.

@sricho
Last active December 29, 2015 01:19
Show Gist options
  • Save sricho/7592697 to your computer and use it in GitHub Desktop.
Save sricho/7592697 to your computer and use it in GitHub Desktop.
Batch coupon generation
class Coupon::BatchGenerator
def self.generate(options = {})
new(options).generate
end
private_class_method :new
def initialize(options)
@options = defaults.merge(options)
end
def generate
Array.new(@options[:count]).map do
create_coupon.tap do |coupon|
coupon.code = coupon_code_with_prefix while !coupon.save
end
end
end
private
def defaults
{
:name => "Not set",
:expiry => 1.week.from_now,
:discount => 0,
:count => 1,
:coupon_length => 4,
:one_time_use => true,
:prefix => ""
}
end
def create_coupon
Coupon.new(:name => @options[:name],
:description => @options[:description],
:expiry => @options[:expiry],
:code => coupon_code_with_prefix,
:discount_percentage => @options[:discount],
:one_time_use => @options[:one_time_use])
end
def coupon_code
random_code.first(@options[:coupon_length])
end
def coupon_code_with_prefix
@options[:prefix] + coupon_code
end
def random_code
SecureRandom.urlsafe_base64.tr('^A-Za-z0-9','')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment