Shortener 可让您轻松为 Rails 应用创建缩短的 URL。
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.
The majority of the Shortener consists of three parts:
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.
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+.
There have been some breaking changes:
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:
class AddExpiresAtToShortenedUrl "shortener/shortened_urls#show"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;
Shortener.unique_key_length = 6By default, when a unique key isn't matched the site is redirected to "/". You can change that by specifying a different url like so;
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:
Shortener.charset = :alphanumcaseIf 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:
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
Shortener.auto_clean_url = trueTo generate a Shortened URL object for the URL "http://example.com" within your controller / models do the following:
Shortener::ShortenedUrl.generate("http://example.com")Alternatively, you can create a shortened url to a relative path within your application:
Shortener::ShortenedUrl.generate("/relative-path?param=whatever")To generate and display a shortened URL in your application use the helper method:
short_url("http://example.com")Pass in subdomain, protocol and other options that the UrlHelper url_for accepts:
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.
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:
class User "shortener/shortened_urls#show"
endParameters 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.
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:
class MyMailer "http://shortener.host"
endThe interceptor supports a few more arguments, see the implementation for details.
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:
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
endThe ::Shortener::ShortenedUrl.fetch_with_token(token: token, additional_params: params) does the following:
note: If no shortened URL is found, the url will be default_redirect or /
You can store a shortened_urls table in another database and connecting to it by creating a initializer with the following:
ActiveSupport.on_load(:shortener_record) do
connects_to(database: { writing: :dbname, reading: :dbname_replica })
endNote: Please, replace dbname and dbname_replica to match your database configuration.
Shortener has one write operation that happens on a GET request. To allow this you can override this method in an initializer.
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)
endWe 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:
Note: We adhere to the community driven Ruby style guide: https://github.com/bbatsov/ruby-style-guide
暂无开放 Issues,或尚未同步最近议题。