Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
ChartURL / Knowtify.io 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 ChartURL.com account
# These are real credentials that we use for a public test account.
CHARTURL_KEY = "dek-d7a46236eda961a6c3c18ffcc6b077ba87d27e9ae85f7842c6d427c265dd5f69d5131308d93332353d4a55a4b1160fcf516515a4a9f0aa50fbf2d7a2e7d0f1c5"
CHARTURL_PROJECT_TOKEN = "dt-RwYN"
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 = OpenSSL::Cipher.new 'AES-256-CBC'
cipher.encrypt
iv = cipher.random_iv
cipher.key = OpenSSL::Digest::SHA256.new(CHARTURL_KEY).digest
encrypted_json = cipher.update(json) + cipher.final
iv_for_url = CGI.escape(Base64.encode64(iv))
data_for_url = CGI.escape(Base64.encode64(encrypted_json))
url = "https://charturl.com/i/#{CHARTURL_PROJECT_TOKEN}/#{template}/#{iv_for_url}/#{data_for_url}"
if url.size > 1500
short_url_for(template, options)
else
url
end
end
def self.short_url_for template, options
url = "https://charturl.com/short-urls.json?api_key=#{API_KEY}"
headers = {'Content-Type' => 'application/json'}
body = options.merge(template: template).to_json
surl_response = Typhoeus::Request.post(url, body: body, headers: headers)
raise("Error creating ShortURL: #{surl_response.inspect}") if !surl_response.success?
JSON.parse(surl_response.body)['short_url']
end
end
# Do whatever you need to create data
def data_for_chart
{
options: {
data: {
columns: [
['Last week'] + 7.times.map { rand(40) + 10 },
['This week'] + 7.times.map { rand(20) + 20 }
]
}
}
}
end
# Generate the URL. The first parameter, `weekly-activity`, is the slug
# for a template you create over at ChartURL.com. This template contains
# your style and chart options like axes labels, typography, etc....
def charturl_url
ChartURL.url_for('weekly-activity', data_for_chart)
end
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.