has_unique_slug 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/lib/has_unique_slug/version.rb +1 -1
- data/lib/has_unique_slug.rb +20 -16
- metadata +3 -3
data/lib/has_unique_slug.rb
CHANGED
@@ -7,27 +7,20 @@ module HasUniqueSlug
|
|
7
7
|
|
8
8
|
module ClassMethods
|
9
9
|
|
10
|
-
def has_unique_slug(
|
11
|
-
|
12
|
-
# Setup options Hash
|
13
|
-
options = {:generates_with => :title, :slug_column => :slug}
|
14
|
-
options.merge! args.pop if args.last.kind_of? Hash
|
15
|
-
|
16
|
-
# Standaridize implementation
|
17
|
-
title, slug = options[:generates_with], options[:slug_column]
|
10
|
+
def has_unique_slug(title_col = "title", slug_col = "slug")
|
18
11
|
|
19
12
|
# Add ActiveRecord Callback
|
20
13
|
before_create do |record|
|
21
14
|
|
22
15
|
# Add a slug if slug doesn't exist
|
23
|
-
if record[
|
24
|
-
record[
|
16
|
+
if record[slug_col].blank?
|
17
|
+
record[slug_col] = record[title_col].parameterize
|
25
18
|
end
|
26
19
|
|
27
20
|
# Ensure the current slug is unique in the database, if not, make it unqiue
|
28
21
|
i = 2
|
29
|
-
while not record.class.where(
|
30
|
-
record[
|
22
|
+
while not record.class.where("#{slug_col} = ?", record[slug_col]).count.zero?
|
23
|
+
record[slug_col] = "#{record[slug_col]}-#{i}"
|
31
24
|
i += 1
|
32
25
|
end
|
33
26
|
end
|
@@ -37,13 +30,24 @@ module HasUniqueSlug
|
|
37
30
|
include HasUniqueSlug::InstanceMethods
|
38
31
|
end
|
39
32
|
|
40
|
-
# Add
|
33
|
+
# Add configuration mechanism
|
34
|
+
instance_eval <<-EOV
|
35
|
+
def slug_column
|
36
|
+
'#{slug_col}'
|
37
|
+
end
|
38
|
+
|
39
|
+
def title_column
|
40
|
+
'#{title_col}'
|
41
|
+
end
|
42
|
+
EOV
|
43
|
+
|
44
|
+
# Add find method to override ActiveRecord::Base.find
|
41
45
|
instance_eval do
|
42
46
|
def find(*args)
|
43
47
|
if args.length == 1
|
44
|
-
where(
|
48
|
+
where("#{slug_column} = ?", args.first).first
|
45
49
|
else
|
46
|
-
where(
|
50
|
+
where("#{slug_column} IN (?)", args)
|
47
51
|
end
|
48
52
|
end
|
49
53
|
end
|
@@ -54,7 +58,7 @@ module HasUniqueSlug
|
|
54
58
|
module InstanceMethods
|
55
59
|
|
56
60
|
def to_param
|
57
|
-
|
61
|
+
self.send(self.class.slug_column)
|
58
62
|
end
|
59
63
|
|
60
64
|
end
|
metadata
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: has_unique_slug
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
hash:
|
4
|
+
hash: 25
|
5
5
|
prerelease:
|
6
6
|
segments:
|
7
7
|
- 0
|
8
8
|
- 1
|
9
|
-
-
|
10
|
-
version: 0.1.
|
9
|
+
- 1
|
10
|
+
version: 0.1.1
|
11
11
|
platform: ruby
|
12
12
|
authors:
|
13
13
|
- Brendan Stennett
|