Socket
Book a DemoInstallSign in
Socket

dynamic_links

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dynamic_links

0.3.0
bundlerRubygems
Version published
Maintainers
1
Created
Source

Unit Tests

DynamicLinks is a flexible URL shortening Ruby gem, designed to provide various strategies for URL shortening, similar to Firebase Dynamic Links.

By default, encoding strategies such as MD5 will generate the same short URL for the same input URL. This behavior ensures consistency and prevents the creation of multiple records for identical URLs. For scenarios requiring unique short URLs for each request, strategies like RedisCounterStrategy can be used, which generate a new short URL every time, regardless of the input URL.

Usage

To use DynamicLinks, you need to configure the shortening strategy and other settings in an initializer or before you start shortening URLs.

Configuration

In your Rails initializer or similar setup code, configure DynamicLinks like this:

DynamicLinks.configure do |config|
  config.shortening_strategy = :md5  # Default strategy
  config.redis_config = { host: 'localhost', port: 6379 }  # Redis configuration
  config.redis_pool_size = 10  # Redis connection pool size
  config.redis_pool_timeout = 3  # Redis connection pool timeout in seconds
  config.enable_rest_api = true  # Enable or disable REST API feature

  # New configuration added in PR #88
  config.enable_fallback_mode = false  # When true, falls back to Firebase URL if a short link is not found
  config.firebase_host = "https://example.app.goo.gl"  # Firebase host URL for fallbacks
end

Development Environment

This project supports two development environment options: GitHub Codespaces and local Docker Compose.

Option 1: GitHub Codespaces

This project is configured to work with GitHub development containers, providing a consistent development environment.

Opening in GitHub Codespaces

  • Navigate to the GitHub repository
  • Click the "Code" button
  • Select the "Codespaces" tab
  • Click "Create codespace on main"

Development in the Codespace

Once the development container is created and set up:

  • The container includes Ruby 3.2, PostgreSQL, Redis, and other dependencies
  • Run the test suite: cd test/dummy && bin/rails test
  • Start the Rails server: cd test/dummy && bin/rails server

Option 2: Local Development with Docker Compose

For local development, we use Docker Compose with VS Code's Remote - Containers extension.

Prerequisites

Opening in VS Code with Containers

  • Clone the repository to your local machine
  • Open the project folder in VS Code
  • VS Code will detect the devcontainer configuration and prompt you to reopen in a container
  • Click "Reopen in Container"

Working with the Docker Compose Setup

  • The setup includes three services: app (Ruby), postgres (PostgreSQL), and redis (Redis)
  • Database and Redis connections are automatically configured
  • Use VS Code tasks (F1 -> "Tasks: Run Task") for common operations like:
    • Starting the Rails server
    • Running tests
    • Running the Rails console
    • Managing Docker Compose services

For more details on the Docker Compose setup, refer to the Docker Compose documentation. 4. Access the application at the forwarded port (usually port 3000)

Shortening a URL

To shorten a URL, simply call:

shortened_url = DynamicLinks.shorten_url("https://example.com")

To find an existing short link for a URL:

short_link_data = DynamicLinks.find_short_link("https://example.com", client)
if short_link_data
  puts short_link_data[:short_url]  # e.g., "https://client.com/abc123"
  puts short_link_data[:full_url]   # e.g., "https://example.com"
else
  puts "No existing short link found"
end

REST API

DynamicLinks provides a REST API for URL shortening operations when enable_rest_api is set to true in the configuration.

Authentication

All API endpoints require an api_key parameter that corresponds to a registered client.

Endpoints

Creates a new short link for a URL.

Endpoint: POST /v1/shortLinks

Parameters:

  • url (required): The URL to shorten
  • api_key (required): Client API key

Example Request:

curl -X POST "http://localhost:3000/v1/shortLinks" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/long-url",
    "api_key": "your-api-key"
  }'

Example Response:

{
  "shortLink": "https://your-domain.com/abc123",
  "previewLink": "https://your-domain.com/abc123?preview=true",
  "warning": []
}

Finds an existing short link for a URL, or creates a new one if none exists. This prevents duplicate short links for the same URL and client.

Endpoint: POST /v1/shortLinks/findOrCreate

Parameters:

  • url (required): The URL to find or shorten
  • api_key (required): Client API key

Example Request:

curl -X POST "http://localhost:3000/v1/shortLinks/findOrCreate" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/long-url",
    "api_key": "your-api-key"
  }'

Example Response (existing link found):

{
  "shortLink": "https://your-domain.com/abc123",
  "previewLink": "https://your-domain.com/abc123?preview=true",
  "warning": []
}

Example Response (new link created):

{
  "shortLink": "https://your-domain.com/def456",
  "previewLink": "https://your-domain.com/def456?preview=true",
  "warning": []
}

Retrieves the original URL from a short link.

Endpoint: GET /v1/shortLinks/{short_url}

Parameters:

  • short_url (in URL): The short URL code to expand
  • api_key (required): Client API key

Example Request:

curl "http://localhost:3000/v1/shortLinks/abc123?api_key=your-api-key"

Example Response:

{
  "url": "https://example.com/long-url"
}

Error Responses

The API returns appropriate HTTP status codes and error messages:

  • 400 Bad Request: Invalid URL format
  • 401 Unauthorized: Invalid or missing API key
  • 403 Forbidden: REST API feature is disabled
  • 404 Not Found: Short link not found (expand endpoint)
  • 500 Internal Server Error: Server error

Example Error Response:

{
  "error": "Invalid URL"
}

Available Shortening Strategies

DynamicLinks supports various shortening strategies. The default strategy is MD5, but you can choose among several others, including NanoIdStrategy, RedisCounterStrategy, Sha256Strategy, and more.

Depending on the strategy you choose, you may need to install additional dependencies.

Optional Dependencies

  • For NanoIdStrategy, add gem 'nanoid', '~> 2.0' to your Gemfile.
  • For RedisCounterStrategy, ensure Redis is available and configured. Redis strategy requires connection_pool gem too.

Ensure you bundle these dependencies along with the DynamicLinks gem if you plan to use these strategies.

Installation

Add this line to your application's Gemfile:

gem "dynamic_links"

And then execute:

$ bundle

Or install it yourself as:

$ gem install dynamic_links

Performance

Benchmarking scripts are available in the benchmarks/ directory to measure performance:

  • ruby_api.rb: Benchmarks Ruby API URL shortening performance
  • rest_api.py: Benchmarks REST API URL shortening performance
  • create_or_find.rb: Compares performance of different create_or_find methods

You can run these benchmarks to measure performance in your specific environment.

How to run the unit test

When using a Plain PostgreSQL DB

rails db:setup
rails db:test:prepare
rails test

When using PostgreSQL DB with Citus

export CITUS_ENABLED=true
rails db:setup
rails db:test:prepare
rails test

Note: Make sure the Citus extension already enabled on the installed PostgreSQL We don't manage it on Rails.

License

The gem is available as open source under the terms of the MIT License.

FAQs

Package last updated on 25 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.