Class: Depository::Collection
- Inherits:
-
Object
- Object
- Depository::Collection
- Extended by:
- Forwardable
- Defined in:
- lib/depository/collection.rb
Class Method Summary collapse
- .config ⇒ Object
- .convert(attrs) ⇒ Object
- .create(attrs) ⇒ Object
- .db ⇒ Object
- .delete(key) ⇒ Object
- .find(key) ⇒ Object
- .find_by(key, value) ⇒ Object
- .join_as(table, *args, &blk) ⇒ Object
- .save(model) ⇒ Object
- .scope(name, blk) ⇒ Object
- .update(*args, &blk) ⇒ Object
Class Method Details
.config ⇒ Object
18 19 20 |
# File 'lib/depository/collection.rb', line 18 def config @_config ||= CollectionConfig.new end |
.convert(attrs) ⇒ Object
72 73 74 75 76 77 78 79 80 81 |
# File 'lib/depository/collection.rb', line 72 def convert(attrs) case attrs when Array attrs.map(&method(:convert)) when Hash config.model.new(Serialize.unpack(config, attrs)) else raise UnknownConversionType, "unable to convert #{attrs.inspect}" end end |
.create(attrs) ⇒ Object
47 48 49 |
# File 'lib/depository/collection.rb', line 47 def create(attrs) save(config.model.new(attrs)) end |
.db ⇒ Object
22 23 24 |
# File 'lib/depository/collection.rb', line 22 def db Result.new(config.db, self) end |
.delete(key) ⇒ Object
68 69 70 |
# File 'lib/depository/collection.rb', line 68 def delete(key) db.where(config.primary_key => key).delete end |
.find(key) ⇒ Object
59 60 61 62 63 64 65 66 |
# File 'lib/depository/collection.rb', line 59 def find(key) result = key.nil? ? nil : where(config.primary_key => key).first raise RecordNotFound, "no record found in collection with id `#{key.inspect}'" if result.nil? return result end |
.find_by(key, value) ⇒ Object
30 31 32 |
# File 'lib/depository/collection.rb', line 30 def find_by(key, value) where(key => value).first end |
.join_as(table, *args, &blk) ⇒ Object
83 84 85 |
# File 'lib/depository/collection.rb', line 83 def join_as(table, *args, &blk) select(*config.model._fields.map { |f| :"#{table}__#{f}"}).join(*args, &blk) end |
.save(model) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/depository/collection.rb', line 34 def save(model) pkey = config.primary_key if new?(model) model.send(:"#{pkey}=", db.insert(Serialize.pack(config, model))) else db.where(pkey => model.send(pkey)). update(Serialize.pack(config, model)) end return model end |
.scope(name, blk) ⇒ Object
26 27 28 |
# File 'lib/depository/collection.rb', line 26 def scope(name, blk) define_singleton_method(name) { |*args| instance_exec *args, &blk } end |
.update(*args, &blk) ⇒ Object
51 52 53 54 55 56 57 |
# File 'lib/depository/collection.rb', line 51 def update(*args, &blk) model = find(*args) blk.call(model) save(model) model end |