Module: Uniqable::ClassMethods
- Defined in:
- lib/uniqable.rb
Overview
Methods going to be AR model’s methods
Instance Method Summary collapse
-
#find_uniqable(uid) ⇒ self
Find record by one of the uniq field usage @example: uniqable :uid, :slug …
-
#find_uniqable!(uid) ⇒ self
Same as method above just raise exception if nothing is there.
-
#uniqable(*fields, to_param: nil) ⇒ Object
Uniqable fields and options declaration @example: uniqable :uid, :slug, to_param: :uid rubocop:disable Metrics/MethodLength.
- #where_uniqable(uid) ⇒ self
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
49 50 51 |
# File 'lib/uniqable.rb', line 49 def find_uniqable(uid) where_uniqable(uid).take end |
#find_uniqable!(uid) ⇒ self
Same as method above just raise exception if nothing is there
55 56 57 |
# File 'lib/uniqable.rb', line 55 def find_uniqable!(uid) where_uniqable(uid).take! end |
#uniqable(*fields, to_param: nil) ⇒ Object
Uniqable fields and options declaration @example:
uniqable :uid, :slug, to_param: :uid
rubocop:disable Metrics/MethodLength
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/uniqable.rb', line 18 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 return if to_param.blank? # :to_param option define_method :to_param do public_send(to_param) end end |
#where_uniqable(uid) ⇒ self
36 37 38 39 40 41 |
# File 'lib/uniqable.rb', line 36 def where_uniqable(uid) where_sql = key_uid?(uid) ? uniqable_fields.map { |r| "#{table_name}.#{r} = :uid" }.join(' OR ') : "#{table_name}.#{primary_key} = :uid" where(where_sql, uid: uid) end |