Sha256: eade8d9f92200ef8a90fe574943e3d298975ca0ce517ad6a12998a914a19505b

Contents?: true

Size: 864 Bytes

Versions: 1

Compression:

Stored size: 864 Bytes

Contents

require 'kramdown'
require 'digest/sha1'

module MarkdownCache
  class Renderer
    EXPIRE = 7 * 24 * 3600  # 7 days

    def render(text)
      return "" if text.nil?
      from_cache(key(Digest::SHA1.hexdigest(text))) do
        kramdown_render(text)
      end
    end

    private

    def kramdown_render(text)
      Kramdown::Document.new(text, kramdown_options).to_html
    end

    def kramdown_options
      {
        input: 'GFM',
        syntax_highlighter: 'rouge'
      }
    end

    def from_cache(key, &block)
      if (value = redis.get(key)).nil?
        value = yield(self)
        redis.set(key, Marshal.dump(value))
        redis.expire(key, EXPIRE)
        value
      else
        Marshal.load(value)
      end
    end

    def key(sha)
      "markdown:#{sha}"
    end

    def redis
      MarkdownCache.configuration.redis
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
markdown_cache-0.1.0 lib/markdown_cache/renderer.rb