Skip to content

Instantly share code, notes, and snippets.

@cflipse
Last active August 29, 2015 14:13
Show Gist options
  • Save cflipse/62b3c832d25815306d04 to your computer and use it in GitHub Desktop.
Save cflipse/62b3c832d25815306d04 to your computer and use it in GitHub Desktop.
daily random shuffle
class WidgetShuffleMigration
def change
change_table :widgets do |t|
# used to store the result of a rand() function, which satisifies: 0 < rand() < 1
t.float :shuffle_order, index: true
end
end
end
class Widget < ActiveRecord::Base
# Reorder is an AR thing that will clear any previous order clauses,
# which is important when you're trying to shuffle things.
scope :shuffled, -> { reorder("shuffle_order") }
# Seed value must be numeric; defaults to yearmonthday
# Which means that the shuffle will produce the same results during the same day
def self.shuffle(seed = :default)
if seed == :default
seed = Date.today.strftime("%Y%m%d")
end
seed = connection.quote(seed)
update_all "shuffle_order = rand(#{seed})"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment