Skip to content

Instantly share code, notes, and snippets.

@esebastian
Last active March 27, 2016 19:02
Show Gist options
  • Save esebastian/9723d6ccaa541c0dcc03 to your computer and use it in GitHub Desktop.
Save esebastian/9723d6ccaa541c0dcc03 to your computer and use it in GitHub Desktop.
VLCTechHub: event collection `created_at` and `slug` generator
require 'dotenv'
require 'uri'
require 'mongo'
require 'active_support/inflector'
Dotenv.load
def format_uri(uri)
index = (uri =~ /@/)
index = (uri =~ /\/{2}/) + 1 unless index
uri[index+1..-1]
end
def slug_for(title, id)
id = id.to_s.chars
suffix = id.first(8).join + id.last(4).join # hex values: generation_time + counter
slug = ActiveSupport::Inflector.transliterate(title)
slug = "#{slug.downcase.strip.gsub(/[^\w-]/, '-')}-#{suffix}".squeeze('-')
slug.sub(/^-/, '')
end
db_uri = ENV['MONGODB_URI']
puts "Updating database at #{format_uri(db_uri)}"
print "Press 'Y' to continue, anything else to abort (y/N) "
abort "Aborting!" if gets.downcase != "y\n"
print "Processing... "
Mongo::Logger.logger.level = ::Logger::ERROR
db = Mongo::Client.new(db_uri)
db['events'].find.each do |event|
created_at = event['created_at'] || event['_id'].generation_time
slug = event['slug'] || slug_for(event['title'], event['_id'])
db['events'].find(_id: event['_id']).update_one({'$set' => {created_at: created_at, slug: slug}})
end
db['events'].indexes.create_one({ :slug => 1 }, :unique => true)
puts "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment