Skip to content

Instantly share code, notes, and snippets.

@rfunduk
Created August 16, 2011 15:54
Show Gist options
  • Save rfunduk/1149410 to your computer and use it in GitHub Desktop.
Save rfunduk/1149410 to your computer and use it in GitHub Desktop.
// Note: The functions should be wrapped in "double quotes" the
// same as the keys, I've removed them here for syntax
// highlighting purposes.
{
"_id": "_design/ratings",
"views": {
"by_permalink": {
"reduce": function( keys, values ) {
return sum( values ) / values.length;
},
"map": function( doc ) {
if( doc.type == 'rating' ) emit( doc.permalink, doc.rating );
}
}
}
}
{
"rows": [
{ "key": "forcing-scrollbars", "value": average-rating },
{ "key": "moving-to-passenger", "value": average-rating },
{ "key": "simple-partials", "value": average-rating },
{ "key": "talking-about-dvcs", "value": average-rating },
...
]
}
require 'rubygems'
require 'sinatra'
require 'rest_client'
require 'json'
DB = 'http://localhost:5984/rf'
get '/get_ratings/:permalink' do
data = RestClient.get "#{DB}/_view/ratings/by_permalink?group=true"
result = JSON.parse( data )['rows'].select do |row|
row if row['key'] == params[:permalink]
end
result.first['value'].to_s unless result.empty?
end
post '/rate/:permalink/:rating' do
doc_url = "#{DB}/#{params[:permalink]}"
rev = JSON.parse( RestClient.get( doc_url ) )['_rev'] rescue nil
new_doc = {
'permalink' => params[:permalink],
'rating' => params[:rating].to_i,
'type' => 'rating'
}
new_doc['_rev'] = rev if rev
RestClient.put doc_url, new_doc.to_json,
:content_type => 'application/json'
end
#!/usr/bin/env ruby
require 'rubygems'
require 'rest_client'
require 'json'
DB = "http://localhost:4567/api"
if ARGV.first == 'put'
permalink, rating = ARGV.pop 2
puts RestClient.post "#{DB}/rate/#{permalink}/#{rating}", ''
else
permalink = ARGV.pop
puts RestClient.get "#{DB}/get_ratings/#{permalink}"
end
$ ruby dbtest.rb put awesome-post 5
{"ok":true,"id":"awesome-post","rev":"3451438800"}
$ ruby dbtest.rb get awesome-post
5
$(document).ready( function() {
// ... some other code ...
if( $.fn.rater ) { $('#some_element').rater( opts ); }
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment