* Increase cache TTL for social preview images These are expensive to generate + don't change often. We can have a long cache. Ideally, they would never expire, and get auto evicted by redis when space fills up. But I don't think a `nil` ttl is possible when a default is set in the Rails config (see production.rb). So I set it to a real long value. + test to guard against it accidently being changed. * Try a cache expiration of 6.weeks as suggested by @mstruve in PR
30 lines
981 B
Ruby
30 lines
981 B
Ruby
module HtmlCssToImage
|
|
AUTH = { username: ApplicationConfig["HCTI_API_USER_ID"],
|
|
password: ApplicationConfig["HCTI_API_KEY"] }.freeze
|
|
|
|
FALLBACK_IMAGE = "https://thepracticaldev.s3.amazonaws.com/i/g355ol6qsrg0j2mhngz9.png".freeze
|
|
|
|
CACHE_EXPIRATION = 6.weeks
|
|
|
|
def self.url(html:, css: nil, google_fonts: nil)
|
|
image = HTTParty.post("https://hcti.io/v1/image",
|
|
body: { html: html, css: css, google_fonts: google_fonts },
|
|
basic_auth: AUTH)
|
|
|
|
image["url"] || FALLBACK_IMAGE
|
|
end
|
|
|
|
def self.fetch_url(html:, css: nil, google_fonts: nil)
|
|
cache_key = "htmlcssimage/#{html}/#{css}/#{google_fonts}"
|
|
cached_url = Rails.cache.read(cache_key)
|
|
|
|
return cached_url if cached_url.present?
|
|
|
|
image_url = url(html: html, css: css, google_fonts: google_fonts)
|
|
unless image_url == FALLBACK_IMAGE
|
|
Rails.cache.write(cache_key, image_url, expires_in: CACHE_EXPIRATION)
|
|
end
|
|
|
|
image_url
|
|
end
|
|
end
|