Created
August 7, 2010 07:20
-
-
Save watura/512551 to your computer and use it in GitHub Desktop.
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
require 'json' | |
require 'open-uri' | |
require 'digest' | |
class BackType | |
def self.requires_key?; true; end | |
def initialize(key) | |
@key = key | |
end | |
def said_about(url) | |
api = "http://api.backtype.com/comments/search.json?q=#{url}&key=#{@key}" | |
begin | |
h = JSON.parse(open(api).read) | |
rescue | |
return {:num => 1, :dates => [Time.at(0)]} | |
end | |
dates = h['comments'].map{|comment| Time.parse(comment['comment']['date'])} | |
{ :num => h['totalresults'].to_i, :dates => dates} | |
end | |
end | |
class Delicious | |
def self.requires_key?; false; end | |
def initialize | |
end | |
def said_about(url) | |
api = "http://feeds.delicious.com/v2/json/url/#{Digest::MD5.hexdigest(url)}?count=100" | |
arr = JSON.parse(open(api).read) | |
dates = arr.map{|bkmk| Time.parse(bkmk['dt'])} | |
{ :num => arr.length, :dates => dates} | |
end | |
end | |
class Hatebu | |
def self.requires_key?; false; end | |
def initialize | |
end | |
def said_about(url) | |
api = "http://b.hatena.ne.jp/entry/jsonlite/#{url}" | |
data = open(api).read | |
return { :num => 1,:dates => [Time.at(0)]} if (data = open(api).read) == "null" | |
h = JSON.parse(open(api).read) | |
dates = h['bookmarks'].map{|bkmk| Time.parse(bkmk['timestamp'])} | |
{ :num => h['count'].to_i, :dates => dates} | |
end | |
end | |
class CityOfHypes | |
# Sources below are expected to return a hash like this: | |
# { :dates => Array of DateTime the URL was mentioned | |
# :num => A number of mentions | |
# } | |
# You can add other sources within writing a class keeping above interface | |
@@sources = [BackType, Delicious, Hatebu] | |
@@keys = ['BackType API Key'] # will be pop when treating a source requiring API key | |
def self.search(url) | |
h = { :num => 0, :dates => []} | |
@@sources.each do |interface| | |
obj = ( interface.requires_key? ? interface.new( @@keys.shift) : interface.new) | |
result = obj.said_about(url) | |
h[:num] += result[:num] | |
h[:dates].concat( result[:dates]) | |
end | |
h | |
end | |
def self.score_of(url) | |
# Determines a score by the result of self.search | |
# fomura of score is (Time.now - avg of bookmarks)/(86400 * number of bookmarks) | |
# 86400 = 24 hours ( 60 * 60 *24) | |
# it could be 604800 | |
info = self.search(url) | |
if info[:dates] != [] | |
date_avg = info[:dates].inject(0) { |result, item| result + item.to_i } /info[:dates].size | |
end | |
(Time.now.to_i - date_avg.to_i)/(86400*info[:num]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment