Skip to content

Instantly share code, notes, and snippets.

@jchris
Created September 30, 2008 16:42
Show Gist options
  • Save jchris/13874 to your computer and use it in GitHub Desktop.
Save jchris/13874 to your computer and use it in GitHub Desktop.
class Question < CouchRest::Model
key_accessor :q, :a
end
class Person < CouchRest::Model
key_accessor :name
def last_name
name.last
end
end
class Course < CouchRest::Model
key_accessor :title
cast :questions, :as => ['Question']
cast :professor, :as => 'Person'
view_by :title
end
class Post < CouchRest::Model
# This sets the _id of the document if it is not already set.
# It will only run once so in this case if the slug changes,
# the _id will stay the same.
#
# uniq_id works using the callback mechanism, always comes as the
# last before_create callback.
#
# unique_id :slug
#
# or provide a lambda
unique_id do |post|
post.slug
end
# Creates a view like:
# function(doc) {
# if (doc.type == 'Post' && doc.slug) {
# emit(doc.slug, null);
# }
# }
#
# To load Post documents by slug, call:
# Post.by_slug :key => 'my-slug'
#
# View methods will always return an array of Posts. To load a single Post, use Post.get(id)
#
# To load Post view-rows by slug, call:
# Post.by_slug :key => 'my-slug', :raw => true
view_by :slug
view_by :date
# Creates a view like:
# function(doc) {
# if (doc.type == 'Post' && doc.user_id && doc.date && doc.body) {
# emit([doc.user_id, doc.date], doc.body);
# }
# }
#
# Defines a method (note that default for this one is to return the raw view rows without docs):
# Post.by_user_id_and_date :startkey => [current_user.id], :endkey => [current_user.id, {}]
#
# Sugared version of the same query?
# Post.by_user_id_and_date :user_id => current_user.id, :date => :all
view_by :user_id, :date, :value => :body, :raw => true
# Define a custom view.
# To load posts tagged 'cooking':
# Post.by_tags :key => 'cooking'
#
# To get the raw view results:
# Post.by_tags :key => 'cooking', :raw => true
#
# To run the reduce (always raw, default is group=true)
# Post.by_tags :reduce => true, :group => false
view_by :tags,
:map =>
"function(doc) {
if (doc.type == 'Post' && doc.tags) {
doc.tags.forEach(function(tag){
emit(doc.tag, 1);
});
}
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
# Can we use someone else's code to define the callback system?
before_create :generate_slug_from_title
def generate_slug_from_title
@doc['slug'] = self.title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'')
end
# Instance methods
key_accessor :title, :body, :user_id
key_reader :slug
# You can make dates work nice without magic or special fields
key_writer :date
def date
Time.parse(@doc['date'])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment