Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Paperclip image uploads with fake data - Ruby on Rails Populator / Faker Gems

I am currently trying to populate a development database on a project with a bunch of fake data, to simulate how it will look and operate with hundreds of articles / users. I looked into different gems to do the task - such as Factory Girl, but documentation was very lacking and I didn't get it - but ended up using the Populator and Faker gems and did the following rake task...

namespace :db do
   desc "Testing populator"
   task :populate => :environment do
      require "populator"
      require "faker"

      User.populate 3 do |user|
         name = Faker::Internet.user_name   
         user.name = name
         user.cached_slug = name
         user.email = Faker::Internet.email
         user.created_at = 4.years.ago..Time.now
      end
   end
end

Works great...for text based data. However, all users have an avatar that can be uploaded via Paperclip attachment, as well as all regular content have thumbnail attachments in the same manner.

I understand the Populator gem simply does a straight population to the database and not necessarily running through ActiveRecord validations to do so..therefor I would assume Paperclip can't run to generate all the different thumbnails and needed (and uploaded to the proper directory) for the avatar if I just filled the field with a filepath in the rake task above.

Is there a way to populate fake images, via Populator or another way? Or perhaps a way to point the rake task at a directory of stock images on my hard drive to autogenerate random thumbnails for each record? Took a hunt on Google for a way, but have not turned up much information on the subject.

UPDATE

The final solution, based on pwnfactory's line of thinking...

namespace :db do
  desc "Testing populator"
  task :populate => :environment do
    require "populator"
    require "faker"

    User.populate 3 do |user|
      name = Faker::Internet.user_name
      user.name = name
      user.cached_slug = name
      user.email = Faker::Internet.email
      user.created_at = 4.years.ago..Time.now
    end

    User.all.each { |user| user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample); user.save! }
  end
end

It basically loops back around and uploaded avatars from the sampleimages directory on all the records.

like image 828
Shannon Avatar asked Apr 26 '11 15:04

Shannon


2 Answers

To associate a random image in your task, you could try the following:

user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample)

where sampleimages is a directory containing avatars to be associated at random

like image 189
acw Avatar answered Nov 17 '22 20:11

acw


user.avatar = File.open(Dir['app/assets/images/*.jpg'].sample)
like image 1
Mikhail Chuprynski Avatar answered Nov 17 '22 21:11

Mikhail Chuprynski