Module: Uniqueness::Model::ClassMethods
- Defined in:
- lib/uniqueness/model.rb
Instance Method Summary collapse
-
#has_unique_field(name, options = {}) ⇒ Object
Adds random field support to Rails models.
Instance Method Details
#has_unique_field(name, options = {}) ⇒ Object
Adds random field support to Rails models
Examples:
To auto-generate a new random string for field +foo+
has_unique_field :foo
You can customize the generated string by
passing an hash. The following keys are supported:
+:trigger_on+ when to be generated, can be one of ActiveRecord callbacks (<tt>before_validation</tt>, <tt>before_create</tt>, <tt>before_save</tt>, <tt>after_initialize</tt>), default to <tt>:before_validation</tt>
+:length+ number of characters, defaults to <tt>32</tt>
+:case_sensitive+ defaults to <tt>true</tt>
+:type+ type of string, defaults to <tt>:auto</tt>
can be one of: <tt>:human</tt>, <tt>:auto</tt>
+:blacklist+ characters to exclude when the random
string, defaults to <tt>[]</tt>
+:scope+ defines the `ActiveRecord` `scope` applied before
calculating the `position` field value.
defaults to <tt>[]</tt>
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/uniqueness/model.rb', line 33 def has_unique_field(name, = {}) self. ||= {} self.[name] = Uniqueness..merge() case [:trigger_on] when :before_create before_create :uniqueness_generate when :before_save before_save :uniqueness_generate when :after_initialize after_initialize :uniqueness_generate else before_validation :uniqueness_generate end validate :uniqueness_validation define_method("regenerate_#{name}") { update(name => Uniqueness.generate(self.[name])) } end |