ruby 用于批量创建Spree促销代码的Rake任务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 用于批量创建Spree促销代码的Rake任务相关的知识,希望对你有一定的参考价值。

namespace :spree_tools do
  desc "Generate random coupon codes in bulk."
  task :generate_coupons => :environment do
    puts "How many codes would you like to generate?"
    number_of_codes = STDIN.gets.strip.to_i

    puts "\nHow much would you like this discount to be for?"
    amount = STDIN.gets.strip.to_f

    puts "\nWhat product should this promotion apply for? (use product name)"
    product_name = STDIN.gets.strip.to_s

    puts "\nWhat would you like to name this sequence of promotion codes?"
    puts 'Example: "Groupon" would produce "Groupon 1", "Groupon 2", etc.'
    sequence = STDIN.gets.strip.to_s

    n = 1
    number_of_codes.times do
      code = generate_unique_code
      promo = Spree::Promotion.create(
         name: "#{sequence} #{n}",
         event_name: 'spree.checkout.coupon_code_added',
         match_policy: 'all',
         starts_at: DateTime.yesterday,
         usage_limit: 1,
         code: code
      )
      promo.promotion_actions << Spree::Promotion::Actions::CreateAdjustment.create(
        calculator: Spree::Calculator::FlatRate.new(preferred_amount: amount)
      )
      promo.promotion_rules.create(type: 'Spree::Promotion::Rules::Product')
      promo.promotion_rules.last.products << Spree::Product.find_by(name: product_name)

      File.open('codes.csv', 'a') do |f|
        f << "#{code}, "
      end

      n += 1
    end
  end

  def generate_unique_code
    begin
      code = SecureRandom.hex(6)
    end while Spree::Promotion.exists?(code: code)
    code
  end
end

以上是关于ruby 用于批量创建Spree促销代码的Rake任务的主要内容,如果未能解决你的问题,请参考以下文章

整理Ruby相关的各种概念(rvm, gem, bundle, rake, rails等)

在 Spree 支持的 Ruby on Rails 电子商务应用程序中集成印度支付网关 (CCAvenue)

Rails Guide -- Ruby on Rake

如何在 ruby​​ on rails 的亚马逊 aws 服务器中使用 gem 执行 rake 任务?

如何在 Ruby 脚本中运行 Rake 任务?

heroku 上的破坏 spree_fancy 布局