Creating a rake task for rails or spree

Creating a rake task for rails or spree

namespace :banners do
  desc 'Populate default banners for homepage'
  task :populate => :environment do
    banner = Spree::BannerBox.find_by(category: 'box-1')
    unless banner
      14.times do |x|
        box = "box-#{ x + 1 }"
        banner_values = {
          alt_text: '',
          url: '',
          category: box,
          banner_type: 'photo',
          enabled: true
        }
        banner = Spree::BannerBox.new(banner_values)
        banner.attachment = File.open(File.join(Rails.root, "app/assets/images/home/#{ box }.png"))
        banner.save!
      end

      # boxes type text
      5.times do |box|
        box_category = "box-#{ box + 1 }-text"
        banner_values = {
          alt_text: '',
          url: '',
          banner_type: 'text',
          category: box_category,
          enabled: true
        }
        banner = Spree::BannerBox.new(banner_values)
        banner.attachment = File.open(File.join(Rails.root, "app/assets/images/home/#{ box_category }.png"))
        banner.save!
      end
    end
  end
end


And now you can use it:
Run for listing all the rake task

rake -T

Or just run the task we just created:

be rake banners:populate
No Comments

Post A Comment