Last active
June 26, 2020 14:35
-
-
Save rainerborene/b8549c689857192eb4ae2b0b7846a20d to your computer and use it in GitHub Desktop.
Ruby integration for generating URLs for Bunny CDN.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class Bunny::Url | |
attr_reader :path, :expires_in, :options | |
def initialize(path, options = {}) | |
@path = path.respond_to?(:key) ? path.key : path | |
@expires_in = options.delete(:expires_in) || 1.week | |
@options = options | |
end | |
def expires | |
@expires ||= expires_in.from_now.to_i | |
end | |
def hashable_base | |
"#{security_key}/#{path}#{expires}" | |
end | |
def token | |
Digest::MD5.base64digest(hashable_base).tr("+/", "-_").tr("=", "").strip | |
end | |
def query | |
options.merge(token: token, expires: expires).to_query | |
end | |
def hostname | |
ENV.fetch("BUNNY_HOST") { credentials[:bunny_hostname] } | |
end | |
def security_key | |
ENV.fetch("BUNNY_SECURITY_KEY") { credentials[:bunny_security_key] } | |
end | |
def to_s | |
"https://#{hostname}/#{path}?#{query}" | |
end | |
def inspect | |
"<#{self.class.name} expires=#{expires} token=#{token.inspect}>" | |
end | |
private | |
def credentials | |
Rails.application.credentials | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment