Module: Sequent::Core::Helpers::UniqueKeys::ClassMethods
- Defined in:
- lib/sequent/core/helpers/unique_keys.rb
Instance Attribute Summary collapse
-
#unique_key_definitions ⇒ Object
readonly
Returns the value of attribute unique_key_definitions.
Instance Method Summary collapse
-
#unique_key(scope, *attributes, **kwargs) ⇒ Object
Defines a unique key for your aggregate.
Instance Attribute Details
#unique_key_definitions ⇒ Object (readonly)
Returns the value of attribute unique_key_definitions.
20 21 22 |
# File 'lib/sequent/core/helpers/unique_keys.rb', line 20 def unique_key_definitions @unique_key_definitions end |
Instance Method Details
#unique_key(scope, *attributes, **kwargs) ⇒ Object
Defines a unique key for your aggregate. The first parameter is the scope of the unique constraints, followed by a list of attributes or keywords with blocks to produce the value that needs to be unique.
‘nil` valued keys are ignored when enforcing uniqueness.
Example usage:
“‘ unique_key :user_email, email: ->{ self.email&.downcase } “`
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/sequent/core/helpers/unique_keys.rb', line 34 def unique_key(scope, *attributes, **kwargs) fail ArgumentError, "'#{scope}' is not a symbol" unless scope.is_a?(Symbol) fail ArgumentError, 'attributes must be symbols' unless attributes.all? { |attr| attr.is_a?(Symbol) } @unique_key_definitions ||= {} fail ArgumentError, "duplicate scope '#{scope}'" if @unique_key_definitions.include?(scope) @unique_key_definitions[scope] = attributes.to_h do |attr| [attr, -> { send(attr) }] end.merge( kwargs.transform_values do |attr| attr.is_a?(Symbol) ? -> { send(attr) } : attr end, ) do |key| fail ArgumentError, "duplicate attribute '#{key}'" end end |