Skip to content

Instantly share code, notes, and snippets.

@stevenklise
Created May 13, 2012 05:14
Show Gist options
  • Save stevenklise/2682397 to your computer and use it in GitHub Desktop.
Save stevenklise/2682397 to your computer and use it in GitHub Desktop.
Save chatlogs to file as JSON from Redis
require 'date'
require 'uri'
require 'redis'
require 'json'
# Parse out the parts of the redistogo uri
uri = URI.parse ENV['REDISTOGO_URL']
# Create connection to Redis using the uri info
@redis = Redis.new :host => uri.host, :port => uri.port, :password => uri.password
# Get the number of messages in messages:itp
length = @redis.llen "messages:itp"
# Get all of the messges
@all_messages = @redis.lrange 'messages:itp', 0, length
# Grab messages from each of these 5 dates and write to file.
[7,8,9,10,11].each do |i|
# Construct a date_string and parse it into a Date object
date_string = "2012-05-#{i}"
date = Date.parse date_string
# Get the start and end of the day in unix time
day_start = date.to_time.to_i*1000
day_end = (date+1).to_time.to_i*1000
# Empty array to hold messages
todays_messages = []
@all_messages.each do |message|
# Turn the JSON into a Ruby hash
message = JSON.parse(message)
# Check that the timestamp attribute exists and is within the bounds. If so
# push it on the end of todays_messages
if !message["timestamp"].nil? && message["timestamp"].to_i > day_start && message["timestamp"].to_i < day_end
todays_messages.push message
end
end
# Write the messages to file as JSON
file = File.open("./thesis_week_#{date_string}.js", 'w')
file.write({"#{date_string}" => todays_messages}.to_json)
file.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment