Method: Sequel::Model::ClassMethods#dataset_module
- Defined in:
- lib/sequel/model/base.rb
#dataset_module(mod = nil, &block) ⇒ Object
Extend the dataset with a module, similar to adding a plugin with the methods defined in DatasetMethods. This is the recommended way to add methods to model datasets.
If given an argument, it should be a module, and is used to extend the underlying dataset. Otherwise an anonymous module is created, and if a block is given, it is module_evaled, allowing you do define dataset methods directly using the standard ruby def syntax. Returns the module given or the anonymous module created.
# Usage with existing module
Album.dataset_module Sequel::ColumnsIntrospection
# Usage with anonymous module
Album.dataset_module do
def foo
:bar
end
end
Album.dataset.foo
# => :bar
Album.foo
# => :bar
Any anonymous modules created are actually instances of Sequel::Model::DatasetModule (a Module subclass), which allows you to call the subset method on them, which defines a dataset method that adds a filter. There are also a number of other methods with the same names as the dataset methods, which can use to define named dataset methods:
Album.dataset_module do
where(:released, Sequel[:release_date] <= Sequel::CURRENT_DATE)
order :by_release_date, :release_date
select :for_select_options, :id, :name, :release_date
end
Album.released.sql
# => "SELECT * FROM artists WHERE (release_date <= CURRENT_DATE)"
Album.by_release_date.sql
# => "SELECT * FROM artists ORDER BY release_date"
Album..sql
# => "SELECT id, name, release_date FROM artists"
Album.released.by_release_date..sql
# => "SELECT id, name, release_date FROM artists WHERE (release_date <= CURRENT_DATE) ORDER BY release_date"
The following methods are supported: distinct, eager, exclude, exclude_having, grep, group, group_and_count, group_append, having, limit, offset, order, order_append, order_prepend, select, select_all, select_append, select_group, where, and server.
The advantage of using these DatasetModule methods to define your dataset methods is that they can take advantage of dataset caching to improve performance.
Any public methods in the dataset module will have class methods created that call the method on the dataset, assuming that the class method is not already defined.
329 330 331 332 333 334 335 336 337 338 339 340 |
# File 'lib/sequel/model/base.rb', line 329 def dataset_module(mod = nil, &block) if mod raise Error, "can't provide both argument and block to Model.dataset_module" if block dataset_extend(mod) mod else @dataset_module ||= dataset_module_class.new(self) @dataset_module.module_eval(&block) if block dataset_extend(@dataset_module) @dataset_module end end |