Module: Uniqable::ClassMethods

Defined in:
lib/uniqable.rb

Instance Method Summary collapse

Instance Method Details

#find_uniqable(uid) ⇒ self

Find record by one of the uniq field usage @example:

uniqable :uid, :slug
...
MyModel.find_uniqable params[:uid] # can be uid or slug column

Returns:

  • (self)


37
38
39
40
# File 'lib/uniqable.rb', line 37

def find_uniqable(uid)
  where_sql = uniqable_fields.map{ |r| "#{table_name}.#{r} = :uid"}.join(' OR ')
  self.where(where_sql, uid: uid).take(1)
end

#uniqable(*fields, to_param: nil) ⇒ Object

Uniqable fields and options declaration @example:

uniqable :uid, :slug, to_param: :uid


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/uniqable.rb', line 15

def uniqable(*fields, to_param: nil)
  fields = [:uid] if fields.blank?
  fields.each do |name|
    before_create { |record| record.uniqable_uid(name) }
  end
  define_singleton_method :uniqable_fields do
    fields
  end

  if to_param # :to_param option
    define_method :to_param do
      public_send(to_param)
    end
  end
end