Skip to content

Commit 1b76805

Browse files
committed
feat: helper method
1 parent 9cf6f11 commit 1b76805

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,28 @@
11
module RailsUrlShortener
22
module UrlsHelper
3+
def short_url(url, owner: nil, key: nil, expires_at: nil, category: nil, url_options: {})
4+
url_object = Url.generate(
5+
url,
6+
owner: owner,
7+
key: key,
8+
expires_at: expires_at,
9+
category: category
10+
)
11+
12+
if url_object.errors.empty?
13+
# This must be fixed
14+
# the url_for helper must generate the url
15+
# options = {
16+
# controller: "rails_url_shortener_url/urls",
17+
# action: "show",
18+
# key: url.key
19+
# }.merge(url_options)
20+
21+
# url_for(options)
22+
rails_url_shortener_url + url_object.key
23+
else
24+
url
25+
end
26+
end
327
end
428
end
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
require 'test_helper'
2+
3+
module RailsUrlShortener
4+
class UrlsHelperTest < ActionView::TestCase
5+
test 'generate url' do
6+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
7+
assert_equal short_url(url), "http://test.host/#{Url.where(url: url).first.key}"
8+
end
9+
10+
test 'generate with existing key' do
11+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
12+
assert_equal short_url(url, key: "aE1122"), url
13+
end
14+
15+
test 'generate url with owner' do
16+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
17+
assert_equal short_url(url, owner: users(:one)), "http://test.host/#{Url.where(url: url).first.key}"
18+
assert_equal Url.where(url: url).first.owner, users(:one)
19+
end
20+
21+
test 'generate url with custom key' do
22+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
23+
assert_equal short_url(url, key: "asd"), "http://test.host/#{Url.where(url: url).first.key}"
24+
end
25+
26+
test 'generate url with expires at' do
27+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
28+
assert_equal short_url(url, expires_at: Time.now + 2.hours), "http://test.host/#{Url.where(url: url).first.key}"
29+
assert_equal Url.where(url: url).first.expires_at.utc.ceil, (Time.now.utc + 2.hours).ceil
30+
end
31+
32+
test 'generate url with category' do
33+
url = 'https://www.github.com/a-chacon/rails_url_shortener/asdss'
34+
assert_equal short_url(url, category: 'free'), "http://test.host/#{Url.where(url: url).first.key}"
35+
assert_equal Url.where(url: url).first.category, 'free'
36+
end
37+
end
38+
end

0 commit comments

Comments
 (0)