Method: Sequel::Plugins::DefDatasetMethod::ClassMethods#def_dataset_method
- Defined in:
- lib/sequel/plugins/def_dataset_method.rb
#def_dataset_method(*args, &block) ⇒ Object
If a block is given, define a method on the dataset (if the model currently has an dataset) with the given argument name using the given block. Also define a class method on the model that calls the dataset method. Stores the method name and block so that it can be reapplied if the model’s dataset changes.
If a block is not given, just define a class method on the model for each argument that calls the dataset method of the same argument name.
Using dataset_module is recommended over using this method. In addition to allowing more natural ruby syntax for defining methods manually, it also offers numerous helper methods that make defining common dataset methods more easily, as well as supporting dataset caching (assuming the arguments allow it).
# Add new dataset method and class method that calls it
Artist.def_dataset_method(:by_name){order(:name)}
Artist.where(Sequel[:name].like('A%')).by_name
Artist.by_name.where(Sequel[:name].like('A%'))
# Just add a class method that calls an existing dataset method
Artist.def_dataset_method(:paginate)
Artist.paginate(2, 10)
50 51 52 53 54 55 56 57 58 59 |
# File 'lib/sequel/plugins/def_dataset_method.rb', line 50 def def_dataset_method(*args, &block) raise(Error, "No arguments given") if args.empty? if block raise(Error, "Defining a dataset method using a block requires only one argument") if args.length > 1 dataset_module{define_method(args.first, &block)} else args.each{|arg| def_model_dataset_method(arg)} end end |