Sha256: 909e933607e0923f3e08ee4d29c5f028d1361a9c10c70ff3b4ff0f7ab78ac99e
Contents?: true
Size: 1.97 KB
Versions: 3
Compression:
Stored size: 1.97 KB
Contents
module Toy module Persistence extend ActiveSupport::Concern module ClassMethods def adapter(name=nil, client=nil, options={}) missing_client = !name.nil? && client.nil? raise(ArgumentError, 'Client is required') if missing_client needs_default_adapter = name.nil? && client.nil? assigning_adapter = !name.nil? && !client.nil? if needs_default_adapter @adapter ||= Adapter[:memory].new({}, options) elsif assigning_adapter @adapter = Adapter[name].new(client, options) end @adapter end def create(attrs={}) new(attrs).tap { |doc| doc.save } end def delete(*ids) ids.each { |id| get(id).try(:delete) } end def destroy(*ids) ids.each { |id| get(id).try(:destroy) } end end def adapter self.class.adapter end def initialize(attrs={}) @_new_record = true super end def initialize_from_database(attrs={}) @_new_record = false initialize_attributes_with_defaults send("attributes=", attrs, false) self end def initialize_copy(other) super @_new_record = true @_destroyed = false end def new_record? @_new_record == true end def destroyed? @_destroyed == true end def persisted? !new_record? && !destroyed? end def save(*) new_record? ? create : update end def update_attributes(attrs) self.attributes = attrs save end def destroy delete end def delete @_destroyed = true adapter.delete(id) end private def create persist! end def update persist! end def persist @_new_record = false end def persist! attrs = persisted_attributes attrs.delete('id') # no need to persist id as that is key adapter.write(id, attrs) persist true end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
toystore-0.10.1 | lib/toy/persistence.rb |
toystore-0.10.0 | lib/toy/persistence.rb |
toystore-0.9.0 | lib/toy/persistence.rb |