Skip to content

Instantly share code, notes, and snippets.

@ryana ryana/generate_url.rb
Last active May 25, 2016

What would you like to do?
ChartURL / Integration Example
# Must install the `typhoeus` gem for this example.
require 'typhoeus'
# These dependencies work for Ruby 2.1.2. Earlier versions of
# Ruby may need different requires or gems
require 'json'
require 'openssl'
require 'base64'
require 'cgi'
# You get these from your account
# These are real credentials that we use for a public test account.
CHARTURL_KEY = "dek-d7a46236eda961a6c3c18ffcc6b077ba87d27e9ae85f7842c6d427c265dd5f69d5131308d93332353d4a55a4b1160fcf516515a4a9f0aa50fbf2d7a2e7d0f1c5"
class ChartURL
# This helper will try to generate an encrypted URL. The upside is that it
# does not require an HTTP request to ChartURL. The downside is that the URL
# could end being too long. In that case, it falls back to the
# `ChartURL.short_url_for` method
def self.url_for template, options
json = options.to_json
cipher = 'AES-256-CBC'
iv = cipher.random_iv
cipher.key =
encrypted_json = cipher.update(json) +
iv_for_url = CGI.escape(Base64.encode64(iv))
data_for_url = CGI.escape(Base64.encode64(encrypted_json))
url = "{CHARTURL_PROJECT_TOKEN}/#{template}/#{iv_for_url}/#{data_for_url}"
if url.size > 1500
short_url_for(template, options)
def self.short_url_for template, options
url = "{API_KEY}"
headers = {'Content-Type' => 'application/json'}
body = options.merge(template: template).to_json
surl_response =, body: body, headers: headers)
raise("Error creating ShortURL: #{surl_response.inspect}") if !surl_response.success?
# Do whatever you need to create data
def data_for_chart
options: {
data: {
columns: [
['Last week'] + { rand(40) + 10 },
['This week'] + { rand(20) + 20 }
# Generate the URL. The first parameter, `weekly-activity`, is the slug
# for a template you create over at This template contains
# your style and chart options like axes labels, typography, etc....
def charturl_url
ChartURL.url_for('weekly-activity', data_for_chart)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.