mongoid_shortener 1.0.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.
Files changed (46) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.markdown +118 -0
  3. data/Rakefile +37 -0
  4. data/app/controllers/mongoid_shortener/application_controller.rb +4 -0
  5. data/app/controllers/mongoid_shortener/shortened_urls_controller.rb +19 -0
  6. data/app/helpers/mongoid_shortener/shortened_urls_helper.rb +10 -0
  7. data/app/models/mongoid_shortener/shortened_url.rb +78 -0
  8. data/lib/mongoid_shortener.rb +12 -0
  9. data/lib/mongoid_shortener/engine.rb +5 -0
  10. data/lib/mongoid_shortener/version.rb +3 -0
  11. data/lib/tasks/mongoid_shortener_tasks.rake +4 -0
  12. data/test/dummy/Rakefile +7 -0
  13. data/test/dummy/app/assets/javascripts/application.js +9 -0
  14. data/test/dummy/app/assets/stylesheets/application.css +7 -0
  15. data/test/dummy/app/controllers/application_controller.rb +3 -0
  16. data/test/dummy/app/helpers/application_helper.rb +2 -0
  17. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  18. data/test/dummy/config.ru +4 -0
  19. data/test/dummy/config/application.rb +51 -0
  20. data/test/dummy/config/boot.rb +10 -0
  21. data/test/dummy/config/environment.rb +5 -0
  22. data/test/dummy/config/environments/development.rb +30 -0
  23. data/test/dummy/config/environments/production.rb +60 -0
  24. data/test/dummy/config/environments/test.rb +39 -0
  25. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  26. data/test/dummy/config/initializers/inflections.rb +10 -0
  27. data/test/dummy/config/initializers/mime_types.rb +5 -0
  28. data/test/dummy/config/initializers/secret_token.rb +7 -0
  29. data/test/dummy/config/initializers/session_store.rb +8 -0
  30. data/test/dummy/config/initializers/wrap_parameters.rb +10 -0
  31. data/test/dummy/config/locales/en.yml +5 -0
  32. data/test/dummy/config/mongoid.yml +20 -0
  33. data/test/dummy/config/routes.rb +3 -0
  34. data/test/dummy/log/development.log +6 -0
  35. data/test/dummy/log/test.log +3498 -0
  36. data/test/dummy/public/404.html +26 -0
  37. data/test/dummy/public/422.html +26 -0
  38. data/test/dummy/public/500.html +26 -0
  39. data/test/dummy/public/favicon.ico +0 -0
  40. data/test/dummy/script/rails +6 -0
  41. data/test/functional/mongoid_shortener/shortened_urls_controller_test.rb +32 -0
  42. data/test/mongoid_shortener_test.rb +7 -0
  43. data/test/test_helper.rb +18 -0
  44. data/test/unit/helpers/mongoid_shortener/shortened_urls_helper_test.rb +18 -0
  45. data/test/unit/mongoid_shortener/shortened_url_test.rb +33 -0
  46. metadata +154 -0
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2011 Teng Siong Ong
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.markdown ADDED
@@ -0,0 +1,118 @@
1
+ MongoidShortener
2
+ ================
3
+
4
+ MongoidShortener is a gem that has to be used together with Mongoid to
5
+ shorten URLs. It uses the [yab62][1] gem to convert URLs to base 62
6
+ shortened link.
7
+
8
+ It is based on Rails engine. I have only tested this on Rails 3.1. You
9
+ might have problem using with Rails version less than 3.1.
10
+
11
+ To use MongoidShortener, first you have to install the gem.
12
+
13
+ ```ruby
14
+ # Gemfile
15
+ gem "mongoid_shortener"
16
+ # Terminal
17
+ bundle install
18
+ ```
19
+
20
+ After that, make sure that you have set the `MongoidShortener`'s
21
+ `root_url` and `prefix_url`, you can do this like the following:
22
+
23
+ ```ruby
24
+ # /config/initializers/mongoid_shortener.rb
25
+ MongoidShortener.root_url = "http://dailymus.es"
26
+ MongoidShortener.prefix_url = "http://dailymus.es/~"
27
+ ```
28
+
29
+ `root_url` is the url that gets redirected to if no matched shortened
30
+ url is found.
31
+
32
+ `prefix_url` is the url get prefixed to the unique_key after the base 62
33
+ conversion. For example, if the link `http://google.com` gets converted
34
+ to `xYAwc`. The returned link will be `http://dailymus.es/~xYAwc` for
35
+ the above example code.
36
+
37
+ To use MongoidShortener in your project, it provides you with two simple
38
+ helper functions. One is for internal use and another one is the view
39
+ helper.
40
+
41
+ ```ruby
42
+ MongoidShortener.root_url = "http://dailymus.es"
43
+ MongoidShortener.prefix_url = "http://dailymus.es/~"
44
+
45
+ # helper function
46
+ MongoidShortener.generate("http://google.com") # -> "http://dailymus.es/~xYAwc"
47
+
48
+ # view helper function
49
+ shortened_url("http://google.com") # -> "http://dailymus.es/~xYAwc"
50
+ ```
51
+
52
+ Besides that, MongoidShortener also provides a really good helper controllor that
53
+ you can make use of. To use it, add this particular route to your
54
+ `config/routes.rb`
55
+
56
+ ```ruby
57
+ # config/routes.rb
58
+ match '/:unique_key' => 'mongoid_shortener/shortened_urls#translate', :via => :get, :constraints => { :unique_key => "~.+" }
59
+ ```
60
+
61
+ What this basically does is that it creates a routes that will only
62
+ match anything starts with `/~`. So, when theres is a request that hits
63
+ that route, it will get redirect to the helper controller of
64
+ MongoidShortener.
65
+
66
+ The controller code in fact looks like:
67
+
68
+ ```ruby
69
+ module MongoidShortener
70
+ class ShortenedUrlsController < ApplicationController
71
+ # find the real link for the shortened link key and redirect
72
+ def translate
73
+ # pull the link out of the db
74
+ sl = ShortenedUrl.where(:unique_key => params[:unique_key][1..-1]).first
75
+
76
+ if sl
77
+ sl.inc(:use_count, 1)
78
+ # do a 301 redirect to the destination url
79
+ head :moved_permanently, :location => sl.url
80
+ else
81
+ # if we don't find the shortened link, redirect to the root
82
+ # make this configurable in future versions
83
+ head :moved_permanently, :location => MongoidShortener.root_url
84
+ end
85
+ end
86
+ end
87
+ end
88
+ ```
89
+
90
+ Let me know if you find any bug for this particular plugin.
91
+
92
+ LICENSE
93
+ =======
94
+
95
+ (The MIT License)
96
+
97
+ Copyright (c) 2011 Teng Siong Ong
98
+
99
+ Permission is hereby granted, free of charge, to any person obtaining
100
+ a copy of this software and associated documentation files (the
101
+ 'Software'), to deal in the Software without restriction, including
102
+ without limitation the rights to use, copy, modify, merge, publish,
103
+ distribute, sublicense, and/or sell copies of the Software, and to
104
+ permit persons to whom the Software is furnished to do so, subject to
105
+ the following conditions:
106
+
107
+ The above copyright notice and this permission notice shall be
108
+ included in all copies or substantial portions of the Software.
109
+
110
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
111
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
112
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
113
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
114
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
115
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
116
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
117
+
118
+ [1]: https://github.com/siong1987/yab62
data/Rakefile ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env rake
2
+ begin
3
+ require 'bundler/setup'
4
+ rescue LoadError
5
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
6
+ end
7
+ begin
8
+ require 'rdoc/task'
9
+ rescue LoadError
10
+ require 'rdoc/rdoc'
11
+ require 'rake/rdoctask'
12
+ RDoc::Task = Rake::RDocTask
13
+ end
14
+
15
+ RDoc::Task.new(:rdoc) do |rdoc|
16
+ rdoc.rdoc_dir = 'rdoc'
17
+ rdoc.title = 'MongoidShortener'
18
+ rdoc.options << '--line-numbers'
19
+ rdoc.rdoc_files.include('README.rdoc')
20
+ rdoc.rdoc_files.include('lib/**/*.rb')
21
+ end
22
+
23
+
24
+
25
+ Bundler::GemHelper.install_tasks
26
+
27
+ require 'rake/testtask'
28
+
29
+ Rake::TestTask.new(:test) do |t|
30
+ t.libs << 'lib'
31
+ t.libs << 'test'
32
+ t.pattern = 'test/**/*_test.rb'
33
+ t.verbose = false
34
+ end
35
+
36
+
37
+ task :default => :test
@@ -0,0 +1,4 @@
1
+ module MongoidShortener
2
+ class ApplicationController < ActionController::Base
3
+ end
4
+ end
@@ -0,0 +1,19 @@
1
+ module MongoidShortener
2
+ class ShortenedUrlsController < ApplicationController
3
+ # find the real link for the shortened link key and redirect
4
+ def translate
5
+ # pull the link out of the db
6
+ sl = ShortenedUrl.where(:unique_key => params[:unique_key][1..-1]).first
7
+
8
+ if sl
9
+ sl.inc(:use_count, 1)
10
+ # do a 301 redirect to the destination url
11
+ head :moved_permanently, :location => sl.url
12
+ else
13
+ # if we don't find the shortened link, redirect to the root
14
+ # make this configurable in future versions
15
+ head :moved_permanently, :location => MongoidShortener.root_url
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,10 @@
1
+ module MongoidShortener
2
+ module ShortenedUrlsHelper
3
+ # generate a url from either a url string, or a shortened url object
4
+ def shortened_url(url)
5
+ raise "Only String accepted: #{url}" unless url.class == String
6
+ short_url = MongoidShortener::ShortenedUrl.generate(url)
7
+ short_url
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,78 @@
1
+ module MongoidShortener
2
+ class ShortenedUrl
3
+ include Mongoid::Document
4
+ include Mongoid::Timestamps
5
+
6
+ field :url, :type => String
7
+ field :unique_key, :type => String
8
+ field :use_count, :type => Integer, :default => 0
9
+
10
+ index :url, :unique => true
11
+ index :unique_key, :unique => true
12
+
13
+ URL_PROTOCOL_HTTP = "http://"
14
+
15
+ REGEX_HTTP_URL = /^\s*(http[s]?:\/\/)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\s*$/i
16
+ REGEX_LINK_HAS_PROTOCOL = Regexp.new('\Ahttp:\/\/|\Ahttps:\/\/', Regexp::IGNORECASE)
17
+
18
+ validates_format_of :url, :with => REGEX_HTTP_URL
19
+
20
+ validates_presence_of :url
21
+ validates_uniqueness_of :url
22
+
23
+ validates_presence_of :unique_key
24
+ validates_uniqueness_of :unique_key
25
+
26
+ attr_accessible :url
27
+
28
+ before_validation :clean_destination_url, :init_unique_key, :on => :create
29
+
30
+ # ensure the url starts with it protocol
31
+ def clean_destination_url
32
+ if !self.url.blank? and self.url !~ REGEX_LINK_HAS_PROTOCOL
33
+ self.url.insert(0, URL_PROTOCOL_HTTP)
34
+ end
35
+ end
36
+
37
+ def init_unique_key
38
+ # generate a unique key for the link
39
+ begin
40
+ self.unique_key = YAB62.encode62(ShortenedUrl::count)
41
+ end while ShortenedUrl::where(:unique_key => self.unique_key).first
42
+ end
43
+
44
+ # generate a shortened link from a url
45
+ # link to a user if one specified
46
+ # throw an exception if anything goes wrong
47
+ def self.generate!(orig_url)
48
+ if !orig_url.blank? and orig_url !~ REGEX_LINK_HAS_PROTOCOL
49
+ orig_url.insert(0, URL_PROTOCOL_HTTP)
50
+ end
51
+
52
+ # don't want to generate the link if it has already been generated
53
+ # so check the datastore
54
+ sl = ShortenedUrl.where(:url => orig_url).first
55
+
56
+ return MongoidShortener.prefix_url + sl.unique_key if sl
57
+
58
+ # create the shortened link, storing it
59
+ sl = ShortenedUrl.create!(:url => orig_url)
60
+
61
+ # return the url
62
+ return MongoidShortener.prefix_url + sl.unique_key
63
+ end
64
+
65
+ # return shortened url on success, nil on failure
66
+ def self.generate(orig_url)
67
+ sl = nil
68
+
69
+ begin
70
+ sl = ShortenedUrl::generate!(orig_url)
71
+ rescue
72
+ sl = nil
73
+ end
74
+
75
+ return sl
76
+ end
77
+ end
78
+ end
@@ -0,0 +1,12 @@
1
+ require "mongoid_shortener/engine"
2
+
3
+ module MongoidShortener
4
+ # The prefix_url for generated shortened url
5
+ mattr_accessor :prefix_url, :root_url
6
+ @@root_url = "http://localhost:3000"
7
+ @@prefix_url = "http://localhost:3000/~"
8
+
9
+ def self.generate url
10
+ ShortenedUrl.generate url
11
+ end
12
+ end
@@ -0,0 +1,5 @@
1
+ module MongoidShortener
2
+ class Engine < Rails::Engine
3
+ isolate_namespace MongoidShortener
4
+ end
5
+ end
@@ -0,0 +1,3 @@
1
+ module MongoidShortener
2
+ VERSION = "1.0.1"
3
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :mongoid_shortener do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env rake
2
+ # Add your own tasks in files placed in lib/tasks ending in .rake,
3
+ # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
4
+
5
+ require File.expand_path('../config/application', __FILE__)
6
+
7
+ Dummy::Application.load_tasks
@@ -0,0 +1,9 @@
1
+ // This is a manifest file that'll be compiled into including all the files listed below.
2
+ // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
3
+ // be included in the compiled file accessible from http://example.com/assets/application.js
4
+ // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
5
+ // the compiled file.
6
+ //
7
+ //= require jquery
8
+ //= require jquery_ujs
9
+ //= require_tree .
@@ -0,0 +1,7 @@
1
+ /*
2
+ * This is a manifest file that'll automatically include all the stylesheets available in this directory
3
+ * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
4
+ * the top of the compiled file, but it's generally better to create a new file per style scope.
5
+ *= require_self
6
+ *= require_tree .
7
+ */
@@ -0,0 +1,3 @@
1
+ class ApplicationController < ActionController::Base
2
+ protect_from_forgery
3
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag "application" %>
6
+ <%= javascript_include_tag "application" %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,4 @@
1
+ # This file is used by Rack-based servers to start the application.
2
+
3
+ require ::File.expand_path('../config/environment', __FILE__)
4
+ run Dummy::Application
@@ -0,0 +1,51 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ # Pick the frameworks you want:
4
+ # require "active_record/railtie"
5
+ require "action_controller/railtie"
6
+ require "action_mailer/railtie"
7
+ require "active_resource/railtie"
8
+ require "sprockets/railtie"
9
+ require "rails/test_unit/railtie"
10
+
11
+ Bundler.require
12
+ require "mongoid_shortener"
13
+
14
+ module Dummy
15
+ class Application < Rails::Application
16
+ # Settings in config/environments/* take precedence over those specified here.
17
+ # Application configuration should go into files in config/initializers
18
+ # -- all .rb files in that directory are automatically loaded.
19
+
20
+ # Custom directories with classes and modules you want to be autoloadable.
21
+ # config.autoload_paths += %W(#{config.root}/extras)
22
+
23
+ # Only load the plugins named here, in the order given (default is alphabetical).
24
+ # :all can be used as a placeholder for all plugins not explicitly named.
25
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
26
+
27
+ # Activate observers that should always be running.
28
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
29
+
30
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
31
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
32
+ # config.time_zone = 'Central Time (US & Canada)'
33
+
34
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
35
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
36
+ # config.i18n.default_locale = :de
37
+
38
+ # Configure the default encoding used in templates for Ruby 1.9.
39
+ config.encoding = "utf-8"
40
+
41
+ # Configure sensitive parameters which will be filtered from the log file.
42
+ config.filter_parameters += [:password]
43
+
44
+ # Enable the asset pipeline
45
+ config.assets.enabled = true
46
+
47
+ # Version of your assets, change this if you want to expire all your assets
48
+ config.assets.version = '1.0'
49
+ end
50
+ end
51
+
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ gemfile = File.expand_path('../../../../Gemfile', __FILE__)
3
+
4
+ if File.exist?(gemfile)
5
+ ENV['BUNDLE_GEMFILE'] = gemfile
6
+ require 'bundler'
7
+ Bundler.setup
8
+ end
9
+
10
+ $:.unshift File.expand_path('../../../../lib', __FILE__)