Module: Sequel::Plugins::DefaultsSetter
- Defined in:
- lib/sequel/plugins/defaults_setter.rb
Overview
The defaults_setter plugin makes the column getter methods return the default values for new objects, if the values have not already been set. Example:
# column a default NULL
# column b default 2
album = Album.new
album.a # => nil
album.b # => 2
album = Album.new(a: 1, b: 3)
album.a # => 1
album.b # => 3
You can manually set default values as well:
Album.default_values[:a] = 4
Album.new.a # => 4
You can also provide procs to set default values:
Album.default_values[:a] = lambda{Date.today}
Album.new.a # => Date.today
If the proc accepts a single argument, it is passed the instance, allowing default values to depend on instance-specific state:
Album.default_values[:a] = lambda{|album| album.b + 1}
Album.new(b: 10).a # => 11
By default, default values returned are not cached:
Album.new.a.equal?(Album.new.a) # => false
However, you can turn on caching of default values:
Album.plugin :defaults_setter, cache: true
Album.new.a.equal?(Album.new.a) # => false
Note that if the cache is turned on, the cached values are stored in the values hash:
Album.plugin :defaults_setter, cache: true
album = Album.new
album.values # => {}
album.a
album.values # => {:a => Date.today}
Usage:
# Make all model subclass instances set defaults (called before loading subclasses)
Sequel::Model.plugin :defaults_setter
# Make the Album class set defaults
Album.plugin :defaults_setter
Defined Under Namespace
Modules: ClassMethods, InstanceMethods
Class Method Summary collapse
-
.configure(model, opts = OPTS) ⇒ Object
Set the default values based on the model schema.
Class Method Details
.configure(model, opts = OPTS) ⇒ Object
Set the default values based on the model schema. Options:
- :cache
-
Cache default values returned in the model’s values hash.
63 64 65 66 67 68 |
# File 'lib/sequel/plugins/defaults_setter.rb', line 63 def self.configure(model, opts=OPTS) model.instance_exec do set_default_values @cache_default_values = opts[:cache] if opts.has_key?(:cache) end end |