Created
October 18, 2013 03:51
-
-
Save kascote/7036248 to your computer and use it in GitHub Desktop.
Utility function to reindex an Ohm model or populate a new added index
This file contains 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
# | |
# Utility function to reindex an Ohm model or populate a new added index | |
# The functions is idempotent | |
# only use over 'index', not 'reference' indexes | |
# | |
# use: | |
# class Table < Ohm::Model | |
# include OhmUtils | |
# | |
# ... | |
# attribute :new_field | |
# ... | |
# ... | |
# index :new_field | |
# ... | |
# end | |
# | |
# | |
# Table.reindex(:new_field) | |
# | |
module OhmUtils | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def reindex(indice) | |
raise 'only indexes, no references' if indice.to_s[-3..-1] == '_id' | |
raise 'index name not found' unless self.indices.include?(indice) | |
self.all.each do |item| | |
self.db.sadd "#{item.send(:model)}:indices:#{indice.to_s}:#{item.send(indice)}", item.id | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice try but I think it's simpler to just Class.all.map(&:save). This way Ohm will recreate the index for you.