Skip to content

Instantly share code, notes, and snippets.

@kascote
Created October 18, 2013 03:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kascote/7036248 to your computer and use it in GitHub Desktop.
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
#
# 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
@phuongnd08
Copy link

Nice try but I think it's simpler to just Class.all.map(&:save). This way Ohm will recreate the index for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment