Skip to content

Commit

Permalink
Allow to specify default options for mutations
Browse files Browse the repository at this point in the history
Change-Id: Ifc183a942bf810d4977b7fd93816adfebcb15bb2
  • Loading branch information
avsej committed Sep 23, 2012
1 parent 023bc58 commit 15aebc0
Showing 1 changed file with 33 additions and 18 deletions.
51 changes: 33 additions & 18 deletions lib/couchbase/model.rb
Expand Up @@ -163,6 +163,14 @@ def self.design_document(name = nil)
end
end

def self.defaults(options = nil)
if options
@_defaults = options
else
@_defaults || {}
end
end

# Ensure that design document is up to date.
#
# @since 0.1.0
Expand Down Expand Up @@ -406,23 +414,28 @@ def self.create(*args)
#
# @param [Hash] attrs attribute-value pairs
def initialize(attrs = {})
if attrs.respond_to?(:with_indifferent_access)
attrs = attrs.with_indifferent_access
end
@id = attrs.delete(:id)
@key = attrs.delete(:key)
@value = attrs.delete(:value)
@doc = attrs.delete(:doc)
@meta = attrs.delete(:meta)
@_attributes = ::Hash.new do |h, k|
default = self.class.attributes[k]
h[k] = if default.respond_to?(:call)
default.call
else
default
end
case attrs
when Hash, HashWithIndifferentAccess
if attrs.respond_to?(:with_indifferent_access)
attrs = attrs.with_indifferent_access
end
@id = attrs.delete(:id)
@key = attrs.delete(:key)
@value = attrs.delete(:value)
@doc = attrs.delete(:doc)
@meta = attrs.delete(:meta)
@_attributes = ::Hash.new do |h, k|
default = self.class.attributes[k]
h[k] = if default.respond_to?(:call)
default.call
else
default
end
end
update_attributes(@doc || attrs)
else
@_raw = attrs
end
update_attributes(@doc || attrs)
end

# Create this model and assign new id if necessary
Expand All @@ -439,7 +452,8 @@ def initialize(attrs = {})
# p.create
def create
@id ||= Couchbase::Model::UUID.generator.next(1, model.thread_storage[:uuid_algorithm])
model.bucket.add(@id, attributes_with_values)
value = @_raw ? @_raw : attributes_with_values
model.bucket.add(@id, value, model.defaults)
self
end

Expand All @@ -456,7 +470,8 @@ def create
# p.save
def save(cas = nil)
return create if new?
model.bucket.replace(@id, attributes_with_values, :cas => cas)
value = @_raw ? @_raw : attributes_with_values
model.bucket.replace(@id, value, model.default.merge(:cas => cas))
self
end

Expand Down

0 comments on commit 15aebc0

Please sign in to comment.