Last active
August 29, 2015 14:13
-
-
Save cflipse/62b3c832d25815306d04 to your computer and use it in GitHub Desktop.
daily random shuffle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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