Module: DataMapper::Model
- Extended by:
- Chainable
- Defined in:
- lib/dm-core/model.rb,
lib/dm-core/model/is.rb,
lib/dm-core/model/hook.rb,
lib/dm-core/model/scope.rb,
lib/dm-core/model/property.rb,
lib/dm-core/model/relationship.rb
Defined Under Namespace
Modules: Hook, Is, Property, Relationship, Scope
Instance Attribute Summary collapse
- #base_model ⇒ Object readonly
Class Method Summary collapse
-
.append_extensions(*extensions) ⇒ Boolean
Extends the model with this module after Resource has been included.
-
.append_inclusions(*inclusions) ⇒ Boolean
Appends a module for inclusion into the model class after Resource.
-
.descendants ⇒ DescendantSet
Return all models that extend the Model module.
- .extended(descendant) ⇒ Object private
-
.extra_extensions ⇒ Set
private
The current registered extra extensions.
-
.extra_inclusions ⇒ Set
private
The current registered extra inclusions.
-
.new(storage_name = nil, &block) ⇒ Model
Creates a new Model class with default_storage_name
storage_name
. -
.raise_on_save_failure ⇒ Boolean
Return if Resource#save should raise an exception on save failures (globally).
-
.raise_on_save_failure=(raise_on_save_failure) ⇒ Boolean
Specify if Resource#save should raise an exception on save failures (globally).
Instance Method Summary collapse
- #[](*args) ⇒ Object (also: #slice)
-
#all(query = Undefined) ⇒ Collection
Find a set of records matching an optional set of conditions.
- #at(*args) ⇒ Object
-
#copy(source_repository_name, target_repository_name, query = {}) ⇒ Collection
Copy a set of records from one repository to another.
-
#create(attributes = {}) ⇒ Resource
Create a Resource.
-
#create!(attributes = {}) ⇒ Resource
Create a Resource, bypassing hooks.
- #default_order(repository_name = default_repository_name) ⇒ Object
- #default_repository_name ⇒ Object
-
#descendants ⇒ Set
Return all models that inherit from a Model.
-
#destroy ⇒ Boolean
Remove all Resources from the repository.
-
#destroy! ⇒ Boolean
Remove all Resources from the repository, bypassing validation.
- #each(&block) ⇒ Object
- #fetch(*args, &block) ⇒ Object
-
#first(*args) ⇒ Resource, Collection
Return the first Resource or the first N Resources for the Model with an optional query.
-
#first_or_create(conditions = {}, attributes = {}) ⇒ Resource
Finds the first Resource by conditions, or creates a new Resource with the attributes if none found.
-
#first_or_new(conditions = {}, attributes = {}) ⇒ Resource
Finds the first Resource by conditions, or initializes a new Resource with the attributes if none found.
-
#get(*key) ⇒ Resource?
Grab a single record by its key.
-
#get!(*key) ⇒ Resource
Grab a single record just like #get, but raise an ObjectNotFoundError if the record doesn’t exist.
-
#last(*args) ⇒ Resource, Collection
Return the last Resource or the last N Resources for the Model with an optional query.
-
#load(records, query) ⇒ Resource
Loads an instance of this Model, taking into account IdentityMap lookup, inheritance columns(s) and Property typecasting.
-
#raise_on_save_failure ⇒ Boolean
Return if Resource#save should raise an exception on save failures (per-model).
-
#raise_on_save_failure=(raise_on_save_failure) ⇒ Boolean
Specify if Resource#save should raise an exception on save failures (per-model).
-
#repositories ⇒ Set
private
Gets the current Set of repositories for which this Model has been defined (beyond default).
-
#repository(name = nil, &block) ⇒ Object, Respository
private
Get the repository with a given name, or the default one for the current context, or the default one for this class.
-
#repository_name ⇒ String
private
Get the current
repository_name
for this Model. - #reverse ⇒ Object
-
#storage_name(repository_name = default_repository_name) ⇒ String
Gets the name of the storage receptacle for this resource in the given Repository (ie., table name, for database stores).
-
#storage_names ⇒ Hash(Symbol => String)
the names of the storage receptacles for this resource across all repositories.
-
#update(attributes) ⇒ Boolean
Update every Resource.
-
#update!(attributes) ⇒ Boolean
Update every Resource, bypassing validations.
- #values_at(*args) ⇒ Object
Methods included from Chainable
Methods included from Scope
#current_scope, #default_scope, #query
Methods included from Is
Instance Attribute Details
#base_model ⇒ Object (readonly)
646 647 648 |
# File 'lib/dm-core/model.rb', line 646 def base_model @base_model end |
Class Method Details
.append_extensions(*extensions) ⇒ Boolean
Extends the model with this module after Resource has been included.
This is a useful way to extend Model while still retaining a self.extended method.
187 188 189 190 191 192 193 194 195 196 |
# File 'lib/dm-core/model.rb', line 187 def self.append_extensions(*extensions) extra_extensions.concat extensions # Add the extension to existing descendants descendants.each do |model| extensions.each { |extension| model.extend(extension) } end true end |
.append_inclusions(*inclusions) ⇒ Boolean
Appends a module for inclusion into the model class after Resource.
This is a useful way to extend Resource while still retaining a self.included method.
156 157 158 159 160 161 162 163 164 165 |
# File 'lib/dm-core/model.rb', line 156 def self.append_inclusions(*inclusions) extra_inclusions.concat inclusions # Add the inclusion to existing descendants descendants.each do |model| inclusions.each { |inclusion| model.send :include, inclusion } end true end |
.descendants ⇒ DescendantSet
Return all models that extend the Model module
class Foo
include DataMapper::Resource
end
DataMapper::Model.descendants.first #=> Foo
59 60 61 |
# File 'lib/dm-core/model.rb', line 59 def self.descendants @descendants ||= DescendantSet.new end |
.extended(descendant) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/dm-core/model.rb', line 208 def self.extended(descendant) descendants << descendant descendant.instance_variable_set(:@valid, false) descendant.instance_variable_set(:@base_model, descendant) descendant.instance_variable_set(:@storage_names, {}) descendant.instance_variable_set(:@default_order, {}) descendant.extend(Chainable) extra_extensions.each { |mod| descendant.extend(mod) } extra_inclusions.each { |mod| descendant.send(:include, mod) } end |
.extra_extensions ⇒ Set
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The current registered extra extensions
203 204 205 |
# File 'lib/dm-core/model.rb', line 203 def self.extra_extensions @extra_extensions ||= [] end |
.extra_inclusions ⇒ Set
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The current registered extra inclusions
172 173 174 |
# File 'lib/dm-core/model.rb', line 172 def self.extra_inclusions @extra_inclusions ||= [] end |
.new(storage_name = nil, &block) ⇒ Model
Creates a new Model class with default_storage_name storage_name
If a block is passed, it will be eval’d in the context of the new Model
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/dm-core/model.rb', line 23 def self.new(storage_name = nil, &block) model = Class.new model.class_eval <<-RUBY, __FILE__, __LINE__ + 1 include DataMapper::Resource def self.name to_s end RUBY if storage_name warn "Passing in +storage_name+ to #{name}.new is deprecated (#{caller[0]})" model.class_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.default_storage_name #{DataMapper::Inflector.classify(storage_name).inspect}.freeze end RUBY end model.instance_eval(&block) if block model end |
.raise_on_save_failure ⇒ Boolean
Return if Resource#save should raise an exception on save failures (globally)
This is false by default.
DataMapper::Model.raise_on_save_failure # => false
92 93 94 95 96 97 98 |
# File 'lib/dm-core/model.rb', line 92 def self.raise_on_save_failure if defined?(@raise_on_save_failure) @raise_on_save_failure else false end end |
.raise_on_save_failure=(raise_on_save_failure) ⇒ Boolean
Specify if Resource#save should raise an exception on save failures (globally)
109 110 111 |
# File 'lib/dm-core/model.rb', line 109 def self.raise_on_save_failure=(raise_on_save_failure) @raise_on_save_failure = raise_on_save_failure end |
Instance Method Details
#[](*args) ⇒ Object Also known as: slice
296 297 298 |
# File 'lib/dm-core/model.rb', line 296 def [](*args) all[*args] end |
#all(query = Undefined) ⇒ Collection
Find a set of records matching an optional set of conditions. Additionally, specify the order that the records are return.
Zoo.all # all zoos
Zoo.all(:open => true) # all zoos that are open
Zoo.all(:opened_on => start..end) # all zoos that opened on a date in the date-range
Zoo.all(:order => [ :tiger_count.desc ]) # Ordered by tiger_count
338 339 340 341 342 343 344 345 |
# File 'lib/dm-core/model.rb', line 338 def all(query = Undefined) if query.equal?(Undefined) || (query.kind_of?(Hash) && query.empty?) # TODO: after adding Enumerable methods to Model, try to return self here new_collection(self.query.dup) else new_collection(scoped_query(query)) end end |
#at(*args) ⇒ Object
302 303 304 |
# File 'lib/dm-core/model.rb', line 302 def at(*args) all.at(*args) end |
#copy(source_repository_name, target_repository_name, query = {}) ⇒ Collection
Copy a set of records from one repository to another.
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 |
# File 'lib/dm-core/model.rb', line 539 def copy(source_repository_name, target_repository_name, query = {}) target_properties = properties(target_repository_name) query[:fields] ||= properties(source_repository_name).select do |property| target_properties.include?(property) end repository(target_repository_name) do |repository| resources = [] all(query.merge(:repository => source_repository_name)).each do |resource| new_resource = new query[:fields].each { |property| new_resource.__send__("#{property.name}=", property.get(resource)) } resources << new_resource if new_resource.save end all(Query.target_query(repository, self, resources)) end end |
#create(attributes = {}) ⇒ Resource
Create a Resource
458 459 460 |
# File 'lib/dm-core/model.rb', line 458 def create(attributes = {}) _create(attributes) end |
#create!(attributes = {}) ⇒ Resource
Create a Resource, bypassing hooks
471 472 473 |
# File 'lib/dm-core/model.rb', line 471 def create!(attributes = {}) _create(attributes, false) end |
#default_order(repository_name = default_repository_name) ⇒ Object
654 655 656 |
# File 'lib/dm-core/model.rb', line 654 def default_order(repository_name = default_repository_name) @default_order[repository_name] ||= key(repository_name).map { |property| Query::Direction.new(property) }.freeze end |
#default_repository_name ⇒ Object
649 650 651 |
# File 'lib/dm-core/model.rb', line 649 def default_repository_name Repository.default_name end |
#descendants ⇒ Set
Return all models that inherit from a Model
class Foo
include DataMapper::Resource
end
class Bar < Foo
end
Foo.descendants.first #=> Bar
78 79 80 |
# File 'lib/dm-core/model.rb', line 78 def descendants @descendants ||= DescendantSet.new end |
#destroy ⇒ Boolean
Remove all Resources from the repository
511 512 513 |
# File 'lib/dm-core/model.rb', line 511 def destroy all.destroy end |
#destroy! ⇒ Boolean
Remove all Resources from the repository, bypassing validation
521 522 523 |
# File 'lib/dm-core/model.rb', line 521 def destroy! all.destroy! end |
#each(&block) ⇒ Object
318 319 320 321 |
# File 'lib/dm-core/model.rb', line 318 def each(&block) all.each(&block) self end |
#fetch(*args, &block) ⇒ Object
306 307 308 |
# File 'lib/dm-core/model.rb', line 306 def fetch(*args, &block) all.fetch(*args, &block) end |
#first(*args) ⇒ Resource, Collection
Return the first Resource or the first N Resources for the Model with an optional query
When there are no arguments, return the first Resource in the Model. When the first argument is an Integer, return a Collection containing the first N Resources. When the last (optional) argument is a Hash scope the results to the query.
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
# File 'lib/dm-core/model.rb', line 364 def first(*args) first_arg = args.first last_arg = args.last limit_specified = first_arg.kind_of?(Integer) with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query) limit = limit_specified ? first_arg : 1 query = with_query ? last_arg : {} query = self.query.slice(0, limit).update(query) if limit_specified all(query) else query.repository.read(query).first end end |
#first_or_create(conditions = {}, attributes = {}) ⇒ Resource
Finds the first Resource by conditions, or creates a new Resource with the attributes if none found
445 446 447 |
# File 'lib/dm-core/model.rb', line 445 def first_or_create(conditions = {}, attributes = {}) first(conditions) || create(conditions.merge(attributes)) end |
#first_or_new(conditions = {}, attributes = {}) ⇒ Resource
Finds the first Resource by conditions, or initializes a new Resource with the attributes if none found
430 431 432 |
# File 'lib/dm-core/model.rb', line 430 def first_or_new(conditions = {}, attributes = {}) first(conditions) || new(conditions.merge(attributes)) end |
#get(*key) ⇒ Resource?
Grab a single record by its key. Supports natural and composite key lookups as well.
Zoo.get(1) # get the zoo with primary key of 1.
Zoo.get!(1) # Or get! if you want an ObjectNotFoundError on failure
Zoo.get('DFW') # wow, support for natural primary keys
Zoo.get('Metro', 'DFW') # more wow, composite key look-up
272 273 274 275 276 277 278 279 |
# File 'lib/dm-core/model.rb', line 272 def get(*key) assert_valid_key_size(key) repository = self.repository key = self.key(repository.name).typecast(key) repository.identity_map(self)[key] || first(key_conditions(repository, key)) end |
#get!(*key) ⇒ Resource
Grab a single record just like #get, but raise an ObjectNotFoundError if the record doesn’t exist.
292 293 294 |
# File 'lib/dm-core/model.rb', line 292 def get!(*key) get(*key) || raise(ObjectNotFoundError, "Could not find #{self.name} with key #{key.inspect}") end |
#last(*args) ⇒ Resource, Collection
Return the last Resource or the last N Resources for the Model with an optional query
When there are no arguments, return the last Resource for the Model. When the first argument is an Integer, return a Collection containing the last N Resources. When the last (optional) argument is a Hash scope the results to the query.
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/dm-core/model.rb', line 400 def last(*args) first_arg = args.first last_arg = args.last limit_specified = first_arg.kind_of?(Integer) with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query) limit = limit_specified ? first_arg : 1 query = with_query ? last_arg : {} query = self.query.slice(0, limit).update(query).reverse! if limit_specified all(query) else query.repository.read(query).last end end |
#load(records, query) ⇒ Resource
Loads an instance of this Model, taking into account IdentityMap lookup, inheritance columns(s) and Property typecasting.
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
# File 'lib/dm-core/model.rb', line 569 def load(records, query) repository = query.repository repository_name = repository.name fields = query.fields discriminator = properties(repository_name).discriminator no_reload = !query.reload? field_map = fields.map { |property| [ property, property.field ] }.to_hash records.map do |record| identity_map = nil key_values = nil resource = nil case record when Hash # remap fields to use the Property object record = record.dup field_map.each { |property, field| record[property] = record.delete(field) if record.key?(field) } model = discriminator && discriminator.load(record[discriminator]) || self model_key = model.key(repository_name) resource = if model_key.valid?(key_values = record.values_at(*model_key)) identity_map = repository.identity_map(model) identity_map[key_values] end resource ||= model.allocate fields.each do |property| next if no_reload && property.loaded?(resource) value = record[property] # TODO: typecasting should happen inside the Adapter # and all values should come back as expected objects value = property.load(value) property.set!(resource, value) end when Resource model = record.model model_key = model.key(repository_name) resource = if model_key.valid?(key_values = record.key) identity_map = repository.identity_map(model) identity_map[key_values] end resource ||= model.allocate fields.each do |property| next if no_reload && property.loaded?(resource) property.set!(resource, property.get!(record)) end end resource.instance_variable_set(:@_repository, repository) if identity_map resource.persisted_state = Resource::State::Clean.new(resource) unless resource.persisted_state? # defer setting the IdentityMap so second level caches can # record the state of the resource after loaded identity_map[key_values] = resource else resource.persisted_state = Resource::State::Immutable.new(resource) end resource end end |
#raise_on_save_failure ⇒ Boolean
Return if Resource#save should raise an exception on save failures (per-model)
This delegates to DataMapper::Model.raise_on_save_failure by default.
User.raise_on_save_failure # => false
123 124 125 126 127 128 129 |
# File 'lib/dm-core/model.rb', line 123 def raise_on_save_failure if defined?(@raise_on_save_failure) @raise_on_save_failure else DataMapper::Model.raise_on_save_failure end end |
#raise_on_save_failure=(raise_on_save_failure) ⇒ Boolean
Specify if Resource#save should raise an exception on save failures (per-model)
140 141 142 |
# File 'lib/dm-core/model.rb', line 140 def raise_on_save_failure=(raise_on_save_failure) @raise_on_save_failure = raise_on_save_failure end |
#repositories ⇒ Set
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Gets the current Set of repositories for which this Model has been defined (beyond default)
703 704 705 |
# File 'lib/dm-core/model.rb', line 703 def repositories [ repository ].to_set + @properties.keys.map { |repository_name| DataMapper.repository(repository_name) } end |
#repository(name = nil, &block) ⇒ Object, Respository
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Get the repository with a given name, or the default one for the current context, or the default one for this class.
671 672 673 674 675 676 677 678 679 |
# File 'lib/dm-core/model.rb', line 671 def repository(name = nil, &block) # # There has been a couple of different strategies here, but me (zond) and dkubb are at least # united in the concept of explicitness over implicitness. That is - the explicit wish of the # caller (+name+) should be given more priority than the implicit wish of the caller (Repository.context.last). # DataMapper.repository(name || repository_name, &block) end |
#repository_name ⇒ String
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Get the current repository_name
for this Model.
If there are any Repository contexts, the name of the last one will be returned, else the default_repository_name
of this model will be
690 691 692 693 |
# File 'lib/dm-core/model.rb', line 690 def repository_name context = Repository.context context.any? ? context.last.name : default_repository_name end |
#reverse ⇒ Object
314 315 316 |
# File 'lib/dm-core/model.rb', line 314 def reverse all.reverse end |
#storage_name(repository_name = default_repository_name) ⇒ String
Gets the name of the storage receptacle for this resource in the given Repository (ie., table name, for database stores).
242 243 244 |
# File 'lib/dm-core/model.rb', line 242 def storage_name(repository_name = default_repository_name) storage_names[repository_name] ||= repository(repository_name).adapter.resource_naming_convention.call(default_storage_name).freeze end |
#storage_names ⇒ Hash(Symbol => String)
the names of the storage receptacles for this resource across all repositories
252 253 254 |
# File 'lib/dm-core/model.rb', line 252 def storage_names @storage_names end |
#update(attributes) ⇒ Boolean
Update every Resource
Person.update(:allow_beer => true)
486 487 488 |
# File 'lib/dm-core/model.rb', line 486 def update(attributes) all.update(attributes) end |
#update!(attributes) ⇒ Boolean
Update every Resource, bypassing validations
Person.update!(:allow_beer => true)
501 502 503 |
# File 'lib/dm-core/model.rb', line 501 def update!(attributes) all.update!(attributes) end |
#values_at(*args) ⇒ Object
310 311 312 |
# File 'lib/dm-core/model.rb', line 310 def values_at(*args) all.values_at(*args) end |