Skip to content

Commit

Permalink
Allow to specify default view options
Browse files Browse the repository at this point in the history
Change-Id: Ib3b64950eaf2674338e406e4acd8f0d9839745d3
  • Loading branch information
avsej committed Aug 24, 2012
1 parent f301b10 commit a6aaeb2
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 8 deletions.
35 changes: 27 additions & 8 deletions lib/couchbase/model.rb
Expand Up @@ -22,6 +22,10 @@
require 'couchbase/model/uuid'
require 'couchbase/model/configuration'

unless Object.respond_to?(:singleton_class)
require 'couchbase/model/ext/singleton_class'
end

module Couchbase

# @since 0.0.1
Expand Down Expand Up @@ -271,19 +275,34 @@ def self.attribute(*names)
end
end

# Defines a view for the model
#
# @since 0.0.1
#
# @param [Symbol, String, Array] names names of the views
# @param [Hash] options options passed to the {Couchbase::View}
#
# @example Define some views for a model
# class Post < Couchbase::Model
# view :all, :published
# view :by_rating, :include_docs => false
# end
#
# post = Post.find("hello")
# post.by_rating.each do |r|
# # ...
# end
def self.view(*names)
options = {}
options = {:wrapper_class => self, :include_docs => true}
if names.last.is_a?(Hash)
options = names.pop
options.update(names.pop)
end
names.each do |name|
views << name
self.instance_eval <<-EOV, __FILE__, __LINE__ + 1
def #{name}(params = {})
View.new(bucket, "_design/\#{design_document}/_view/#{name}",
params.merge(:wrapper_class => self, :include_docs => true))
end
EOV
singleton_class.send(:define_method, name) do |*params|
params = options.merge(params.first || {})
View.new(bucket, "_design/#{design_document}/_view/#{name}", params)
end
end
end

Expand Down
24 changes: 24 additions & 0 deletions lib/couchbase/model/ext/singleton_class.rb
@@ -0,0 +1,24 @@
# Author:: Couchbase <info@couchbase.com>
# Copyright:: 2012 Couchbase, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

class Object
def singleton_class
class << self
self
end
end
end

0 comments on commit a6aaeb2

Please sign in to comment.