lib/cachai.rb in cachai-0.1.4 vs lib/cachai.rb in cachai-0.2.0

- old
+ new

@@ -54,11 +54,11 @@ get '/comments.?:format?' do check_domain!(params[:domain]) # puts "Comments for: #{params[:domain]}#{params[:path]}" - json_list = get_comments(params[:path], params[:nocache]) + json_list = Cachai.get_comments_for(params[:path], params[:nocache]) if params[:callback] content_type 'application/javascript' "#{params[:callback]}(#{json_list});" else @@ -66,13 +66,20 @@ end end post '/comments.?:format?' do begin - data = JSON.parse(request.body.read) - check_domain!(data['domain']) + data = params[:format] == 'json' ? JSON.parse(request.body.read) : params + if data[:url] # got single URL with protocol://domain/path + url = URI.parse(data) + data['domain'] = url.host + data['protocol'] = url.schema + data['path'] = url.path + end + + check_domain!(data['domain']) halt(400, "Missing params") if data['protocol'].blank? or data['path'].blank? headers['Access-Control-Allow-Origin'] = data['protocol'] + '//' + data['domain'] permalink = 'http://' + data['domain'] + data['path'] halt(400, "No spam allowed") if is_spam?(data, permalink, request) @@ -128,45 +135,9 @@ end def json(obj) content_type 'application/json' return obj.is_a?(String) ? obj : obj.to_json - end - - def get_comments(path, nocache = false) - key = Cachai.key_for(path) - - unless !nocache && json_list = Cachai.cache.get(key) - puts "Not cached. Getting from DB: #{path}" - - if post = Post.find_by_path(path) - json_list = get_and_sort_comments_for(post).to_json - else - json_list = '[]' - end - - Cachai.cache.set(key, json_list) - Cachai.cache.expire(key, CACHE_MINUTES) - end - - json_list - end - - def get_and_sort_comments_for(post) - result = [] - top_level = post.responses.comment.approved.top_level - nested = post.responses.comment.approved.nested - - top_level.each_with_index do |comment, i| - obj = comment.as_json - children = nested.select do |nested| - nested.parent_id == comment.id - end - obj.merge!(:children => children) if children.any? - result.push(obj) - end - - result end def is_spam?(data, link, request) return false unless @akismet # return true if blacklisted?(name, email, content)