Module: Sequel::Plugins

Defined in:
lib/sequel/model/plugins.rb,
lib/sequel/plugins/enum.rb,
lib/sequel/plugins/list.rb,
lib/sequel/plugins/tree.rb,
lib/sequel/plugins/uuid.rb,
lib/sequel/plugins/dirty.rb,
lib/sequel/plugins/touch.rb,
lib/sequel/plugins/finder.rb,
lib/sequel/plugins/pg_row.rb,
lib/sequel/plugins/caching.rb,
lib/sequel/plugins/sharding.rb,
lib/sequel/plugins/rcte_tree.rb,
lib/sequel/plugins/eager_each.rb,
lib/sequel/plugins/inspect_pk.rb,
lib/sequel/plugins/subclasses.rb,
lib/sequel/plugins/timestamps.rb,
lib/sequel/plugins/composition.rb,
lib/sequel/plugins/active_model.rb,
lib/sequel/plugins/split_values.rb,
lib/sequel/plugins/sql_comments.rb,
lib/sequel/plugins/static_cache.rb,
lib/sequel/plugins/table_select.rb,
lib/sequel/plugins/column_select.rb,
lib/sequel/plugins/serialization.rb,
lib/sequel/plugins/csv_serializer.rb,
lib/sequel/plugins/error_splitter.rb,
lib/sequel/plugins/force_encoding.rb,
lib/sequel/plugins/instance_hooks.rb,
lib/sequel/plugins/throw_failures.rb,
lib/sequel/plugins/update_refresh.rb,
lib/sequel/plugins/xml_serializer.rb,
lib/sequel/plugins/association_pks.rb,
lib/sequel/plugins/boolean_readers.rb,
lib/sequel/plugins/boolean_subsets.rb,
lib/sequel/plugins/columns_updated.rb,
lib/sequel/plugins/defaults_setter.rb,
lib/sequel/plugins/insert_conflict.rb,
lib/sequel/plugins/json_serializer.rb,
lib/sequel/plugins/lazy_attributes.rb,
lib/sequel/plugins/string_stripper.rb,
lib/sequel/extensions/_model_pg_row.rb,
lib/sequel/plugins/accessed_columns.rb,
lib/sequel/plugins/after_initialize.rb,
lib/sequel/plugins/auto_validations.rb,
lib/sequel/plugins/column_conflicts.rb,
lib/sequel/plugins/forbid_lazy_load.rb,
lib/sequel/plugins/instance_filters.rb,
lib/sequel/plugins/inverted_subsets.rb,
lib/sequel/plugins/paged_operations.rb,
lib/sequel/plugins/typecast_on_load.rb,
lib/sequel/plugins/unlimited_update.rb,
lib/sequel/plugins/update_or_create.rb,
lib/sequel/plugins/async_thread_pool.rb,
lib/sequel/plugins/before_after_save.rb,
lib/sequel/plugins/column_encryption.rb,
lib/sequel/plugins/eager_graph_eager.rb,
lib/sequel/plugins/input_transformer.rb,
lib/sequel/plugins/many_through_many.rb,
lib/sequel/plugins/nested_attributes.rb,
lib/sequel/plugins/subset_conditions.rb,
lib/sequel/plugins/blacklist_security.rb,
lib/sequel/plugins/def_dataset_method.rb,
lib/sequel/plugins/hook_class_methods.rb,
lib/sequel/plugins/optimistic_locking.rb,
lib/sequel/plugins/static_cache_cache.rb,
lib/sequel/plugins/update_primary_key.rb,
lib/sequel/plugins/validation_helpers.rb,
lib/sequel/plugins/whitelist_security.rb,
lib/sequel/plugins/association_proxies.rb,
lib/sequel/plugins/prepared_statements.rb,
lib/sequel/plugins/skip_create_refresh.rb,
lib/sequel/plugins/skip_saving_columns.rb,
lib/sequel/plugins/unused_associations.rb,
lib/sequel/plugins/validate_associated.rb,
lib/sequel/plugins/validation_contexts.rb,
lib/sequel/plugins/dataset_associations.rb,
lib/sequel/plugins/require_valid_schema.rb,
lib/sequel/plugins/singular_table_names.rb,
lib/sequel/plugins/delay_add_association.rb,
lib/sequel/plugins/pg_array_associations.rb,
lib/sequel/plugins/constraint_validations.rb,
lib/sequel/plugins/modification_detection.rb,
lib/sequel/plugins/tactical_eager_loading.rb,
lib/sequel/plugins/class_table_inheritance.rb,
lib/sequel/plugins/insert_returning_select.rb,
lib/sequel/plugins/optimistic_locking_base.rb,
lib/sequel/plugins/association_dependencies.rb,
lib/sequel/plugins/concurrent_eager_loading.rb,
lib/sequel/plugins/empty_failure_backtraces.rb,
lib/sequel/plugins/mssql_optimistic_locking.rb,
lib/sequel/plugins/prepared_statements_safe.rb,
lib/sequel/plugins/single_table_inheritance.rb,
lib/sequel/plugins/validation_class_methods.rb,
lib/sequel/plugins/auto_restrict_eager_graph.rb,
lib/sequel/plugins/instance_specific_default.rb,
lib/sequel/plugins/pg_xmin_optimistic_locking.rb,
lib/sequel/plugins/association_multi_add_remove.rb,
lib/sequel/plugins/association_lazy_eager_option.rb,
lib/sequel/plugins/pg_auto_constraint_validations.rb,
lib/sequel/plugins/primary_key_lookup_check_values.rb,
lib/sequel/extensions/_model_constraint_validations.rb,
lib/sequel/plugins/serialization_modification_detection.rb,
lib/sequel/plugins/validation_helpers_generic_type_messages.rb,
lib/sequel/plugins/auto_validations_constraint_validations_presence_message.rb

Overview

Empty namespace that plugins should use to store themselves, so they can be loaded via Model.plugin.

Plugins should be modules with one of the following conditions:

  • A singleton method named apply, which takes a model, additional arguments, and an optional block. This is called the first time the plugin is loaded for this model (unless it was already loaded by an ancestor class), before including/extending any modules, with the arguments and block provided to the call to Model.plugin.

  • A module inside the plugin module named ClassMethods, which will extend the model class.

  • A module inside the plugin module named InstanceMethods, which will be included in the model class.

  • A module inside the plugin module named DatasetMethods, which will extend the model’s dataset.

  • A singleton method named configure, which takes a model, additional arguments, and an optional block. This is called every time the Model.plugin method is called, after including/extending any modules.

Defined Under Namespace

Modules: AccessedColumns, ActiveModel, AfterInitialize, AssociationDependencies, AssociationLazyEagerOption, AssociationMultiAddRemove, AssociationPks, AssociationProxies, AsyncThreadPool, AutoRestrictEagerGraph, AutoValidations, AutoValidationsConstraintValidationsPresenceMessage, BeforeAfterSave, BlacklistSecurity, BooleanReaders, BooleanSubsets, Caching, ClassTableInheritance, ColumnConflicts, ColumnEncryption, ColumnSelect, ColumnsUpdated, Composition, ConcurrentEagerLoading, ConstraintValidations, CsvSerializer, DatasetAssociations, DefDatasetMethod, DefaultsSetter, DelayAddAssociation, Dirty, EagerEach, EagerGraphEager, EmptyFailureBacktraces, Enum, ErrorSplitter, Finder, ForbidLazyLoad, ForceEncoding, HookClassMethods, InputTransformer, InsertConflict, InsertReturningSelect, InspectPk, InstanceFilters, InstanceHooks, InstanceSpecificDefault, InvertedSubsets, JsonSerializer, LazyAttributes, List, ManyThroughMany, ModificationDetection, MssqlOptimisticLocking, NestedAttributes, OptimisticLocking, OptimisticLockingBase, PagedOperations, PgArrayAssociations, PgAutoConstraintValidations, PgRow, PgXminOptimisticLocking, PreparedStatements, PreparedStatementsSafe, PrimaryKeyLookupCheckValues, RcteTree, RequireValidSchema, Serialization, SerializationModificationDetection, Sharding, SingleTableInheritance, SingularTableNames, SkipCreateRefresh, SkipSavingColumns, SplitValues, SqlComments, StaticCache, StaticCacheCache, StringStripper, Subclasses, SubsetConditions, TableSelect, TacticalEagerLoading, ThrowFailures, Timestamps, Touch, Tree, TypecastOnLoad, UnlimitedUpdate, UnusedAssociations, UpdateOrCreate, UpdatePrimaryKey, UpdateRefresh, Uuid, ValidateAssociated, ValidationClassMethods, ValidationContexts, ValidationHelpers, ValidationHelpersGenericTypeMessages, WhitelistSecurity, XmlSerializer

Constant Summary collapse

SEQUEL_METHOD_NAME =

Return a unique method name symbol for the given suffix.

lambda do |suffix|
  :"_sequel_#{suffix}_#{method_num_mutex.synchronize{method_num += 1}}"
end

Class Method Summary collapse

Class Method Details

.after_set_dataset(mod, meth) ⇒ Object

Add method to mod that overrides set_dataset to call the method afterward.



50
51
52
53
54
55
56
57
# File 'lib/sequel/model/plugins.rb', line 50

def self.after_set_dataset(mod, meth)
  mod.send(:define_method, :set_dataset) do |*a|
    r = super(*a)
    # Allow calling private class methods as methods this specifies are usually private
    send(meth)
    r
  end
end

.def_dataset_methods(mod, meths) ⇒ Object

In the given module mod, define methods that are call the same method on the dataset. This is designed for plugins to define dataset methods inside ClassMethods that call the implementations in DatasetMethods.

This should not be called with untrusted input or method names that can’t be used literally, since it uses class_eval.



31
32
33
34
35
36
37
38
# File 'lib/sequel/model/plugins.rb', line 31

def self.def_dataset_methods(mod, meths)
  Array(meths).each do |meth|
    mod.class_eval("def #{meth}(*args, &block); dataset.#{meth}(*args, &block) end", __FILE__, __LINE__)
    # :nocov:
    mod.send(:ruby2_keywords, meth) if respond_to?(:ruby2_keywords, true)
    # :nocov:
  end
end

.def_sequel_method(model, meth, expected_arity, &block) ⇒ Object

Define a private instance method using the block with the provided name and expected arity. If the name is given as a Symbol, it is used directly. If the name is given as a String, a unique name will be generated using that string. The expected_arity should be either 0 (no arguments) or 1 (single argument).

If a block with an arity that does not match the expected arity is used, a deprecation warning will be issued. The method defined should still work, though it will be slower than a method with the expected arity.

Sequel only checks arity for regular blocks, not lambdas. Lambdas were already strict in regards to arity, so there is no need to try to fix arity to keep backwards compatibility for lambdas.

Blocks with required keyword arguments are not supported by this method.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/sequel/model/plugins.rb', line 81

def self.def_sequel_method(model, meth, expected_arity, &block)
  if meth.is_a?(String)
    meth = SEQUEL_METHOD_NAME.call(meth)
  end
  call_meth = meth

  unless block.lambda?
    required_args, optional_args, rest, keyword = _define_sequel_method_arg_numbers(block)

    if keyword == :required
      raise Error, "cannot use block with required keyword arguments when calling define_sequel_method with expected arity #{expected_arity}"
    end

    case expected_arity
    when 0
      unless required_args == 0
        # SEQUEL6: remove
        Sequel::Deprecation.deprecate("Arity mismatch in block passed to define_sequel_method. Expected Arity 0, but arguments required for #{block.inspect}. Support for this will be removed in Sequel 6.")
        b = block
        block = lambda{instance_exec(&b)} # Fallback
      end
    when 1
      if required_args == 0 && optional_args == 0 && !rest
        # SEQUEL6: remove
        Sequel::Deprecation.deprecate("Arity mismatch in block passed to define_sequel_method. Expected Arity 1, but no arguments accepted for #{block.inspect}.  Support for this will be removed in Sequel 6.")
        temp_method = SEQUEL_METHOD_NAME.call("temp")
        model.class_eval("def #{temp_method}(_) #{meth =~ /\A\w+\z/ ? "#{meth}_arity" : "send(:\"#{meth}_arity\")"} end", __FILE__, __LINE__)
        model.send(:alias_method, meth, temp_method)
        model.send(:undef_method, temp_method)
        model.send(:private, meth)
        meth = :"#{meth}_arity"
      elsif required_args > 1
        # SEQUEL6: remove
        Sequel::Deprecation.deprecate("Arity mismatch in block passed to define_sequel_method. Expected Arity 1, but more arguments required for #{block.inspect}.  Support for this will be removed in Sequel 6.")
        b = block
        block = lambda{|r| instance_exec(r, &b)} # Fallback
      end
    else
      raise Error, "unexpected arity passed to define_sequel_method: #{expected_arity.inspect}"
    end
  end

  model.send(:define_method, meth, &block)
  model.send(:private, meth)
  model.send(:alias_method, meth, meth)
  call_meth
end

.inherited_instance_variables(mod, hash) ⇒ Object

Add method to mod that overrides inherited_instance_variables to include the values in this hash.



42
43
44
45
46
47
# File 'lib/sequel/model/plugins.rb', line 42

def self.inherited_instance_variables(mod, hash)
  mod.send(:define_method, :inherited_instance_variables) do ||
    super().merge!(hash)
  end
  mod.send(:private, :inherited_instance_variables)
end