Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

shortener

> 编程语言
Open source

Shortener makes it easy to create shortened URLs for your rails application.

548 stars0 likes0 views
WebsiteGitHub

About

Shortener makes it easy to create shortened URLs for your rails application.

Shortener

Shortener is a Rails Engine Gem that makes it easy to create and interpret shortened URLs on your own domain from within your Rails application. Once installed Shortener will generate, store URLS and "unshorten" shortened URLs for your applications visitors, all whilst collecting basic usage metrics.

Overview

The majority of the Shortener consists of three parts:

  • a model for storing the details of the shortened link;
  • a controller to accept incoming requests and redirecting them to the target URL;
  • a helper for generating shortened URLs from controllers and views.

Dependencies

Shortener is designed to work from within a Ruby on Rail applications. It has dependancies Rails core components like ActiveRecord, ActionController, the rails routing engine and more.

Ruby Version Support

As Ruby 1.9.3 entered end of maintainance in early 2015, the last version of the Shortener gem to support Ruby 1.9.3 is 0.4.x. Shortener v0.5 onwards will require Ruby 2+.

Upgrading

v0.4.0 to v0.5.0

There have been some breaking changes:

  1. The owner argument is passed into the generator and helper methods as a named parameter.
  2. Original URLs arguments without a hypertext protocol (http|https) will be assumed to be relative paths.

v0.5.1 to v0.5.2

v0.5.2 introduced the ability to set an expiration date for a shortened URL. The expiration dates are stored in a expires_at column in the database, which can be added to your schema with the following migration:

ruby
class AddExpiresAtToShortenedUrl  "shortener/shortened_urls#show"

Configuration

The gem can be configured in a config/initializers/shortener.rb file.

By default, the shortener will generate keys that are 5 characters long. You can change that by specifying the length of the key like so;

ruby
Shortener.unique_key_length = 6

By default, when a unique key isn't matched the site is redirected to "/". You can change that by specifying a different url like so;

ruby
Shortener.default_redirect = "http://www.someurl.com"

By default, Shortener will generate unique keys using numbers and lowercase a-z. If you desire more combinations, you can enable the upper and lower case charset, by including the following:

ruby
Shortener.charset = :alphanumcase

If you want to use a custom charset, you can create your own combination by creating an array of possible values, such as allowing underscore and dashes:

ruby
Shortener.charset = ("a".."z").to_a + (0..9).to_a + ["-", "_"]

By default, Shortener assumes URLs to be valid web URLs and normalizes them in an effort to make sure there are no duplicate records generated for effectively same URLs with differences of only non-effective slash etc. You can control this option if it interferes for any of your logic. One common case is for mobile app links or universal links where normalization can corrupt the URLs of form appname://some_route

ruby
Shortener.auto_clean_url = true

Usage

To generate a Shortened URL object for the URL "http://example.com" within your controller / models do the following:

ruby
Shortener::ShortenedUrl.generate("http://example.com")

Alternatively, you can create a shortened url to a relative path within your application:

ruby
Shortener::ShortenedUrl.generate("/relative-path?param=whatever")

To generate and display a shortened URL in your application use the helper method:

ruby
short_url("http://example.com")

Pass in subdomain, protocol and other options that the UrlHelper url_for accepts:

ruby
short_url(
  "http://example.com", 
  url_options: { subdomain: 'foo', host: 'bar', protocol: 'https' } 
)

This will generate a shortened URL. store it to the db and return a string representing the shortened URL.

Shortened URLs with owner

You can link shortened URLs to an owner, to scope them. To do so, add the following line to the models which will act as owners:

ruby
class User  "shortener/shortened_urls#show"
end

URL Parameters

Parameters are passed though from the shortened url, to the destination URL. If the destination URL has the same parameters as the destination URL, the parameters on the shortened url take precedence over those on the destination URL.

For example, if we have an orginal URL of:

http://destination.com?test=yes&happy=defo (identified with token ABCDEF) Which is shortened into: http://coolapp.io/s/ABCDEF?test=no&why=not Then, the resulting URL will be: http://destination.com?test=no&happy=defo&why=not Note how the test parameter takes the value given on the short URL.

Shorten URLs in generated emails

You can register the included mail interceptor to shorten all links in the emails generated by your Rails app. For example, add to your mailer:

ruby
class MyMailer  "http://shortener.host"
end

The interceptor supports a few more arguments, see the implementation for details.

Logging, stats and other tricks

If you want more things to happen when a user accesses one of your short urls, you can create your own show action as follows:

ruby
def show
  token = ::Shortener::ShortenedUrl.extract_token(params[:id])
  url   = ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params)
  # do some logging, store some stats
  redirect_to url[:url], status: :moved_permanently
end

Fetch with Token

The ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params) does the following:

  1. finds the ShortenedUrl for the supplied token
  2. increments the use_count for the retrieved ShortenedURL
  3. combines the additional parameters with the URL in the retrieved ShortenedURL
  4. returns a hash of the format `{url: , shortened_url: }

note: If no shortened URL is found, the url will be default_redirect or /

Configuring a different database for shortened_urls table

You can store a shortened_urls table in another database and connecting to it by creating a initializer with the following:

ruby
ActiveSupport.on_load(:shortener_record) do
  connects_to(database: { writing: :dbname, reading: :dbname_replica })
end

Note: Please, replace dbname and dbname_replica to match your database configuration.

Configuring Reader and Writer Multi-DB Roles

Shortener has one write operation that happens on a GET request. To allow this you can override this method in an initializer.

ruby
module ShortenerWriterMonkeyPatch
  def increment_usage_count
    ActiveRecord::Base.connected_to(role: :writing) do
      self.class.increment_counter(:use_count, id)
    end
  end
end

ActiveSupport.on_load(:shortener_shortened_url) do
  Shortener::ShortenedUrl.prepend(ShortenerWriterMonkeyPatch)
end

Contributing

We welcome new contributors. Because we're all busy people, and because Shortener is used/relied upon by many projects, it is essential that new Pull Requests are opened with good spec coverage, and a passing build on supported ruby versions and Rails versions. Please create a single PR per feature/contribution, with as few changes per PR as possible to make it easier to review.

To contribute:

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Write spec coverage of changes
  4. Commit your changes (git commit -am 'Add some feature')
  5. Push to the branch (git push origin my-new-feature)
  6. Create a new Pull Request
  7. Ensure the build is passing

Note: We adhere to the community driven Ruby style guide: https://github.com/bbatsov/ruby-style-guide

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言