Module: LooseChange::Persistence
- Included in:
- Base
- Defined in:
- lib/loose_change/persistence.rb
Instance Method Summary collapse
-
#create(args = {}) ⇒ Object
Instantiate a new Loose Change record with attributes
args
and immediately save to the database. -
#create!(args = {}) ⇒ Object
Instantiate a new Loose Change record with attributes
args
and immediately save to the database. -
#find(id) ⇒ Object
Retrieve a document from CouchDB with id
id
as a Loose Change instance. -
#instantiate_from_hash(hash) ⇒ Object
Build a Loose Change record from a hash of attributes
hash
as returned by CouchDB. -
#use_database(db, server = "http://127.0.0.1:5984") ⇒ Object
Set the database source for this model, named
db
onserver
(localhost:5984 by default).
Instance Method Details
#create(args = {}) ⇒ Object
Instantiate a new Loose Change record with attributes args
and immediately save to the database.
29 30 31 32 33 |
# File 'lib/loose_change/persistence.rb', line 29 def create(args = {}) model = new(args) model.save model end |
#create!(args = {}) ⇒ Object
Instantiate a new Loose Change record with attributes args
and immediately save to the database. If the record is invalid, a RecordInvalid
error will be thrown.
38 39 40 |
# File 'lib/loose_change/persistence.rb', line 38 def create!(args = {}) new(args).save! end |
#find(id) ⇒ Object
Retrieve a document from CouchDB with id id
as a Loose Change instance.
17 18 19 20 21 22 23 24 25 |
# File 'lib/loose_change/persistence.rb', line 17 def find(id) begin result = JSON.parse(RestClient.get(self.database.uri + "/#{ id }"), default_headers) rescue RestClient::ResourceNotFound raise RecordNotFound end raise RecordNotFound unless result['model_name'] == model_name instantiate_from_hash(result) end |
#instantiate_from_hash(hash) ⇒ Object
Build a Loose Change record from a hash of attributes hash
as returned by CouchDB.
44 45 46 47 48 49 50 51 52 53 |
# File 'lib/loose_change/persistence.rb', line 44 def instantiate_from_hash(hash) model = new(hash.reject {|k, _| 'model_name' == k}) model.id = hash['_id'] model.new_record = false if hash['_attachments'] = hash['_attachments'].map {|name, _| name} model. = .inject({}) {|acc, name| acc[name] = {:content_type => hash['_attachments'][name]['content_type']}; acc} end model end |
#use_database(db, server = "http://127.0.0.1:5984") ⇒ Object
Set the database source for this model, named db
on server
(localhost:5984 by default). If the database does not exist, it will be added.
9 10 11 12 13 14 |
# File 'lib/loose_change/persistence.rb', line 9 def use_database(db, server = "http://127.0.0.1:5984") self.database = Database.new(db, Server.new(server)) Database.setup_design(self.database, self.model_name) view_by_all paginated_view_by_all end |