Module: Sequel::Model::InstanceMethods
- Defined in:
- lib/sequel/model/base.rb
Overview
Sequel::Model instance methods that implement basic model functionality.
-
All of the methods in HOOKS create instance methods that are called by Sequel when the appropriate action occurs. For example, when destroying a model object, Sequel will call before_destroy, do the destroy, and then call after_destroy.
-
The following instance_methods all call the class method of the same name: columns, dataset, db, primary_key, db_schema.
-
The following instance methods allow boolean flags to be set on a per-object basis: raise_on_save_failure, raise_on_typecast_failure, require_modification, strict_param_setting, typecast_empty_string_to_nil, typecast_on_assignment, use_transactions. If they are not used, the object will default to whatever the model setting is.
Instance Attribute Summary collapse
-
#values ⇒ Object
readonly
The hash of attribute values.
Instance Method Summary collapse
-
#==(obj) ⇒ Object
(also: #eql?)
Compares model instances by values.
-
#===(obj) ⇒ Object
If pk is not nil, true only if the objects have the same class and pk.
-
#[](column) ⇒ Object
Returns value of the column’s attribute.
-
#[]=(column, value) ⇒ Object
Sets the value for the given column.
-
#autoincrementing_primary_key ⇒ Object
The autoincrementing primary key for this model object.
-
#changed_columns ⇒ Object
The columns that have been updated.
-
#delete ⇒ Object
Deletes and returns self.
-
#destroy(opts = {}) ⇒ Object
Like delete but runs hooks before and after delete.
-
#each(&block) ⇒ Object
Iterates through all of the current values using each.
-
#errors ⇒ Object
Returns the validation errors associated with this object.
-
#exists? ⇒ Boolean
Returns true when current instance exists, false otherwise.
-
#hash ⇒ Object
Value that should be unique for objects with the same class and pk (if pk is not nil), or the same class and values (if pk is nil).
-
#id ⇒ Object
Returns value for the :id attribute, even if the primary key is not id.
-
#initialize(values = {}, from_db = false) ⇒ Object
Creates new instance and passes the given values to set.
-
#inspect ⇒ Object
Returns a string representation of the model instance including the class name and values.
-
#keys ⇒ Object
Returns the keys in values.
-
#lock! ⇒ Object
Refresh this record using for_update unless this is a new record.
-
#marshallable! ⇒ Object
Remove elements of the model object that make marshalling fail.
-
#modified! ⇒ Object
Explicitly mark the object as modified, so save_changes/update will run callbacks even if no columns have changed.
-
#modified? ⇒ Boolean
Whether this object has been modified since last saved, used by save_changes to determine whether changes should be saved.
-
#new? ⇒ Boolean
Returns true if the current instance represents a new record.
-
#pk ⇒ Object
Returns the primary key value identifying the model instance.
-
#pk_hash ⇒ Object
Returns a hash identifying the model instance.
-
#refresh ⇒ Object
Reloads attributes from database and returns self.
-
#reload ⇒ Object
Alias of refresh, but not aliased directly to make overriding in a plugin easier.
-
#save(*columns) ⇒ Object
Creates or updates the record, after making sure the record is valid.
-
#save_changes(opts = {}) ⇒ Object
Saves only changed columns if the object has been modified.
-
#set(hash) ⇒ Object
Updates the instance with the supplied values with support for virtual attributes, raising an exception if a value is used that doesn’t have a setter method (or ignoring it if strict_param_setting = false).
-
#set_all(hash) ⇒ Object
Set all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.
-
#set_except(hash, *except) ⇒ Object
Set all values using the entries in the hash, except for the keys given in except.
-
#set_only(hash, *only) ⇒ Object
Set the values using the entries in the hash, only if the key is included in only.
-
#this ⇒ Object
Returns (naked) dataset that should return only this instance.
-
#update(hash) ⇒ Object
Runs set with the passed hash and then runs save_changes.
-
#update_all(hash) ⇒ Object
Update all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.
-
#update_except(hash, *except) ⇒ Object
Update all values using the entries in the hash, except for the keys given in except.
-
#update_only(hash, *only) ⇒ Object
Update the values using the entries in the hash, only if the key is included in only.
-
#valid? ⇒ Boolean
Validates the object and returns true if no errors are reported.
-
#validate ⇒ Object
Validates the object.
Instance Attribute Details
#values ⇒ Object (readonly)
The hash of attribute values. Keys are symbols with the names of the underlying database columns.
531 532 533 |
# File 'lib/sequel/model/base.rb', line 531 def values @values end |
Instance Method Details
#==(obj) ⇒ Object Also known as: eql?
Compares model instances by values.
580 581 582 |
# File 'lib/sequel/model/base.rb', line 580 def ==(obj) (obj.class == model) && (obj.values == @values) end |
#===(obj) ⇒ Object
If pk is not nil, true only if the objects have the same class and pk. If pk is nil, false.
587 588 589 |
# File 'lib/sequel/model/base.rb', line 587 def ===(obj) pk.nil? ? false : (obj.class == model) && (obj.pk == pk) end |
#[](column) ⇒ Object
Returns value of the column’s attribute.
559 560 561 |
# File 'lib/sequel/model/base.rb', line 559 def [](column) @values[column] end |
#[]=(column, value) ⇒ Object
Sets the value for the given column. If typecasting is enabled for this object, typecast the value based on the column’s type. If this a a new record or the typecasted value isn’t the same as the current value for the column, mark the column as changed.
567 568 569 570 571 572 573 574 575 576 577 |
# File 'lib/sequel/model/base.rb', line 567 def []=(column, value) # If it is new, it doesn't have a value yet, so we should # definitely set the new value. # If the column isn't in @values, we can't assume it is # NULL in the database, so assume it has changed. v = typecast_value(column, value) if new? || !@values.include?(column) || v != @values[column] changed_columns << column unless changed_columns.include?(column) @values[column] = v end end |
#autoincrementing_primary_key ⇒ Object
The autoincrementing primary key for this model object. Should be overridden if you have a composite primary key with one part of it being autoincrementing.
600 601 602 |
# File 'lib/sequel/model/base.rb', line 600 def autoincrementing_primary_key primary_key end |
#changed_columns ⇒ Object
The columns that have been updated. This isn’t completely accurate, see Model#[]=.
606 607 608 |
# File 'lib/sequel/model/base.rb', line 606 def changed_columns @changed_columns ||= [] end |
#delete ⇒ Object
Deletes and returns self. Does not run destroy hooks. Look into using destroy instead.
612 613 614 615 |
# File 'lib/sequel/model/base.rb', line 612 def delete _delete self end |
#destroy(opts = {}) ⇒ Object
Like delete but runs hooks before and after delete. If before_destroy returns false, returns false without deleting the object the the database. Otherwise, deletes the item from the database and returns self. Uses a transaction if use_transactions is true or if the :transaction option is given and true.
623 624 625 |
# File 'lib/sequel/model/base.rb', line 623 def destroy(opts = {}) checked_save_failure{checked_transaction(opts){_destroy(opts)}} end |
#each(&block) ⇒ Object
Iterates through all of the current values using each.
Example:
Ticket.find(7).each { |k, v| puts "#{k} => #{v}" }
631 632 633 |
# File 'lib/sequel/model/base.rb', line 631 def each(&block) @values.each(&block) end |
#errors ⇒ Object
Returns the validation errors associated with this object.
636 637 638 |
# File 'lib/sequel/model/base.rb', line 636 def errors @errors ||= Errors.new end |
#exists? ⇒ Boolean
Returns true when current instance exists, false otherwise. Generally an object that isn’t new will exist unless it has been deleted.
643 644 645 |
# File 'lib/sequel/model/base.rb', line 643 def exists? this.count > 0 end |
#hash ⇒ Object
Value that should be unique for objects with the same class and pk (if pk is not nil), or the same class and values (if pk is nil).
649 650 651 |
# File 'lib/sequel/model/base.rb', line 649 def hash [model, pk.nil? ? @values.sort_by{|k,v| k.to_s} : pk].hash end |
#id ⇒ Object
Returns value for the :id attribute, even if the primary key is not id. To get the primary key value, use #pk.
655 656 657 |
# File 'lib/sequel/model/base.rb', line 655 def id @values[:id] end |
#initialize(values = {}, from_db = false) ⇒ Object
Creates new instance and passes the given values to set. If a block is given, yield the instance to the block unless from_db is true. This method runs the after_initialize hook after it has optionally yielded itself to the block.
Arguments:
-
values - should be a hash to pass to set.
-
from_db - should only be set by Model.load, forget it exists.
543 544 545 546 547 548 549 550 551 552 553 554 555 556 |
# File 'lib/sequel/model/base.rb', line 543 def initialize(values = {}, from_db = false) if from_db @new = false set_values(values) else @values = {} @new = true @modified = true set(values) changed_columns.clear yield self if block_given? end after_initialize end |
#inspect ⇒ Object
Returns a string representation of the model instance including the class name and values.
661 662 663 |
# File 'lib/sequel/model/base.rb', line 661 def inspect "#<#{model.name} @values=#{inspect_values}>" end |
#keys ⇒ Object
Returns the keys in values. May not include all column names.
666 667 668 |
# File 'lib/sequel/model/base.rb', line 666 def keys @values.keys end |
#lock! ⇒ Object
Refresh this record using for_update unless this is a new record. Returns self.
671 672 673 |
# File 'lib/sequel/model/base.rb', line 671 def lock! new? ? self : _refresh(this.for_update) end |
#marshallable! ⇒ Object
Remove elements of the model object that make marshalling fail. Returns self.
676 677 678 679 |
# File 'lib/sequel/model/base.rb', line 676 def marshallable! @this = nil self end |
#modified! ⇒ Object
Explicitly mark the object as modified, so save_changes/update will run callbacks even if no columns have changed.
683 684 685 |
# File 'lib/sequel/model/base.rb', line 683 def modified! @modified = true end |
#modified? ⇒ Boolean
Whether this object has been modified since last saved, used by save_changes to determine whether changes should be saved. New values are always considered modified.
690 691 692 |
# File 'lib/sequel/model/base.rb', line 690 def modified? @modified || !changed_columns.empty? end |
#new? ⇒ Boolean
Returns true if the current instance represents a new record.
695 696 697 |
# File 'lib/sequel/model/base.rb', line 695 def new? @new end |
#pk ⇒ Object
Returns the primary key value identifying the model instance. Raises an error if this model does not have a primary key. If the model has a composite primary key, returns an array of values.
702 703 704 705 |
# File 'lib/sequel/model/base.rb', line 702 def pk raise(Error, "No primary key is associated with this model") unless key = primary_key key.is_a?(Array) ? key.map{|k| @values[k]} : @values[key] end |
#pk_hash ⇒ Object
Returns a hash identifying the model instance. It should be true that:
Model[model_instance.pk_hash] === model_instance
710 711 712 |
# File 'lib/sequel/model/base.rb', line 710 def pk_hash model.primary_key_hash(pk) end |
#refresh ⇒ Object
Reloads attributes from database and returns self. Also clears all cached association and changed_columns information. Raises an Error if the record no longer exists in the database.
717 718 719 |
# File 'lib/sequel/model/base.rb', line 717 def refresh _refresh(this) end |
#reload ⇒ Object
Alias of refresh, but not aliased directly to make overriding in a plugin easier.
722 723 724 |
# File 'lib/sequel/model/base.rb', line 722 def reload refresh end |
#save(*columns) ⇒ Object
Creates or updates the record, after making sure the record is valid. If the record is not valid, or before_save, before_create (if new?), or before_update (if !new?) return false, returns nil unless raise_on_save_failure is true (if it is true, it raises an error). Otherwise, returns self. You can provide an optional list of columns to update, in which case it only updates those columns.
Takes the following options:
-
:changed - save all changed columns, instead of all columns or the columns given
-
:transaction - set to false not to use a transaction
-
:validate - set to false not to validate the model before saving
739 740 741 742 743 744 745 746 |
# File 'lib/sequel/model/base.rb', line 739 def save(*columns) opts = columns.last.is_a?(Hash) ? columns.pop : {} if opts[:validate] != false and !valid? raise(ValidationFailed.new(errors)) if raise_on_save_failure return end checked_save_failure{checked_transaction(opts){_save(columns, opts)}} end |
#save_changes(opts = {}) ⇒ Object
Saves only changed columns if the object has been modified. If the object has not been modified, returns nil. If unable to save, returns false unless raise_on_save_failure is true.
751 752 753 |
# File 'lib/sequel/model/base.rb', line 751 def save_changes(opts={}) save(opts.merge(:changed=>true)) || false if modified? end |
#set(hash) ⇒ Object
Updates the instance with the supplied values with support for virtual attributes, raising an exception if a value is used that doesn’t have a setter method (or ignoring it if strict_param_setting = false). Does not save the record.
759 760 761 |
# File 'lib/sequel/model/base.rb', line 759 def set(hash) set_restricted(hash, nil, nil) end |
#set_all(hash) ⇒ Object
Set all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.
765 766 767 |
# File 'lib/sequel/model/base.rb', line 765 def set_all(hash) set_restricted(hash, false, false) end |
#set_except(hash, *except) ⇒ Object
Set all values using the entries in the hash, except for the keys given in except.
771 772 773 |
# File 'lib/sequel/model/base.rb', line 771 def set_except(hash, *except) set_restricted(hash, false, except.flatten) end |
#set_only(hash, *only) ⇒ Object
Set the values using the entries in the hash, only if the key is included in only.
777 778 779 |
# File 'lib/sequel/model/base.rb', line 777 def set_only(hash, *only) set_restricted(hash, only.flatten, false) end |
#this ⇒ Object
Returns (naked) dataset that should return only this instance.
782 783 784 |
# File 'lib/sequel/model/base.rb', line 782 def this @this ||= model.dataset.filter(pk_hash).limit(1).naked end |
#update(hash) ⇒ Object
Runs set with the passed hash and then runs save_changes.
787 788 789 |
# File 'lib/sequel/model/base.rb', line 787 def update(hash) update_restricted(hash, nil, nil) end |
#update_all(hash) ⇒ Object
Update all values using the entries in the hash, ignoring any setting of allowed_columns or restricted columns in the model.
793 794 795 |
# File 'lib/sequel/model/base.rb', line 793 def update_all(hash) update_restricted(hash, false, false) end |
#update_except(hash, *except) ⇒ Object
Update all values using the entries in the hash, except for the keys given in except.
799 800 801 |
# File 'lib/sequel/model/base.rb', line 799 def update_except(hash, *except) update_restricted(hash, false, except.flatten) end |
#update_only(hash, *only) ⇒ Object
Update the values using the entries in the hash, only if the key is included in only.
805 806 807 |
# File 'lib/sequel/model/base.rb', line 805 def update_only(hash, *only) update_restricted(hash, only.flatten, false) end |
#valid? ⇒ Boolean
Validates the object and returns true if no errors are reported.
816 817 818 819 820 821 822 823 824 825 |
# File 'lib/sequel/model/base.rb', line 816 def valid? errors.clear if before_validation == false save_failure(:validation) if raise_on_save_failure return false end validate after_validation errors.empty? end |
#validate ⇒ Object
Validates the object. If the object is invalid, errors should be added to the errors attribute. By default, does nothing, as all models are valid by default.
812 813 |
# File 'lib/sequel/model/base.rb', line 812 def validate end |