Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Liquid filters for maliq gem to generate xhtml
# *** ATTENSION ***
# This file is NOT for Jekyll. It's modified for adapting Maliq(https://github.com/melborne/maliq) gem
# which is a EPUB generator.
# 'gem install ruby-aaws' required.
# By: kyoendo(a.k.a melborne) 2012
# Source URL: https://gist.github.com/4134497#file_amazon_liquid_tags.rb
# ------------------------------------
#
# Amazon liquid filters for jekyll - base0.net http://base0.net/posts/amazon-liquid-filters-for-jekyll/
# By: Michael Janssen
require 'amazon/aws'
require 'amazon/aws/search'
require 'cgi'
module Jekyll
class AmazonResultCache
def initialize
@result_cache = {}
end
@@instance = AmazonResultCache.new
def self.instance
@@instance
end
def item_lookup(asin)
strip = asin.to_s.strip
return @result_cache[asin] if @result_cache.has_key?(asin)
il = Amazon::AWS::ItemLookup.new('ASIN', {'ItemId' => asin})
resp = Amazon::AWS::Search::Request.new.search(il)
@result_cache[asin] = resp
return resp
end
private_class_method :new
end
module Filters
def amazon_link(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
url = CGI::unescape(item.detail_page_url.to_s)
title = item.item_attributes.title.to_s.gsub(/ \[Blu-ray\]/, '').gsub(/ \(Ultimate Edition\)/, '')
'<a href="%s">%s</a>' % [url, title]
end
def amazon_authors(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
authors = item.item_attributes.author.collect(&:to_s)
array_to_sentence_string(authors)
end
def amazon_medium_image(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
url = CGI::unescape(item.detail_page_url.to_s)
image_url = save_image item.image_sets.image_set[0].medium_image.url
'<a href="%s"><img class="amazon" src="%s" /></a>' % [url, image_url]
end
def amazon_large_image(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
url = CGI::unescape(item.detail_page_url.to_s)
image_url = save_image item.image_sets.image_set[0].large_image.url
'<a href="%s"><img class="amazon" src="%s" /></a>' % [url, image_url]
end
def amazon_small_image(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
url = CGI.escapeHTML(item.detail_page_url.to_s)
image_url = save_image item.image_sets.image_set[0].small_image.url
'<a href="%s"><img class="amazon" src="%s" /></a>' % [url, image_url]
end
def amazon_release_date(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
item.item_attributes.theatrical_release_date.to_s
end
# Movie specific
def amazon_actors(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
actors = item.item_attributes.actor.collect(&:to_s)
array_to_sentence_string(actors)
end
def amazon_director(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
item.item_attributes.director.to_s
end
def amazon_running_time(text)
resp = AmazonResultCache.instance.item_lookup(text)
item = resp.item_lookup_response[0].items[0].item[0]
item.item_attributes.running_time.to_s + " minutes"
end
end
end
# Followings are added for Maliq gem.
require "open-uri"
class CGI
class << self
alias :unescape :escapeHTML
end
end
module Jekyll
module Filters
def save_image(url, img_dir='images')
url = url[0].to_s
Dir.mkdir(img_dir) unless Dir.exist?(img_dir)
path = "#{img_dir}/#{File.basename(url)}"
unless File.exist?(path)
puts "Image downloading..."
File.open(path, 'w') do |f|
open(url) { |img| f.write img.read }
end
end
path
end
end
end
Liquid::Template.register_filter(Jekyll::Filters)
# A Liquid tag for Maliq that enable adding CSS signatures.
# by: Kyo Endo
# Source URL: https://gist.github.com/
#
# Example usage:
# text = <<-EOS
# {% csssig h2 id='hello' class='header' %}
# ##Hello
# this is test.
# {% endcsssig %}
#
# => <h2 id="hello" class="header">Hello</h2>
#
# <p>this is test.</p>
#
require "liquid"
require "rdiscount"
require "nokogiri"
class CSSSignature < Liquid::Block
def initialize(tag_name, text, token)
super
@text = text
end
def render(context)
tag, *signs = @text.split
_SIG_REG_ = /(\w+)\s*=\s*(?:["']([\w ]*)?["']|(\w+))/
signs = signs.join(' ').scan(_SIG_REG_).map(&:compact)
html = Nokogiri::HTML.fragment RDiscount.new(super).to_html
if target = html.at_css(tag)
signs.each { |attr, val| target[attr] = val }
end
html.to_html
end
end
Liquid::Template.register_tag('csssig', CSSSignature)
if __FILE__ == $0
text = <<-EOS
{% csssig h2 id='hello' class='header hi' %}
##Hello
this is test.
{% endcsssig %}
EOS
puts Liquid::Template.parse(text).render
end
# *** ATTENSION ***
# This file is NOT for Jekyll. It's modified for adapting Maliq(https://github.com/melborne/maliq) gem
# which is a EPUB generator.
# 'gem install pygments.rb' required.
# By: kyoendo(a.k.a melborne) 2012
# Source URL: https://gist.github.com/4134497#file_gist_tag.rb
# ------------------------------------
# A Liquid tag for Jekyll sites that allows embedding Gists and showing code for non-JavaScript enabled browsers and readers.
# by: Brandon Tilly
# Source URL: https://gist.github.com/1027674
# Post http://brandontilley.com/2011/01/31/gist-tag-for-jekyll.html
#
# Example usage: {% gist 1027674 gist_tag.rb %} //embeds a gist for this plugin
require 'cgi'
require 'digest/md5'
require 'net/https'
require 'uri'
module Jekyll
class GistTag < Liquid::Tag
def initialize(tag_name, text, token)
super
@text = text
@cache_disabled = false
@cache_folder = File.expand_path "../.gist-cache", File.dirname(__FILE__)
FileUtils.mkdir_p @cache_folder
end
def render(context)
if parts = @text.match(/([\d]*) (.*)/)
gist, file = parts[1].strip, parts[2].strip
script_url = script_url_for gist, file
code = get_cached_gist(gist, file) || get_gist_from_web(gist, file)
html_output_for script_url, code
else
""
end
end
def html_output_for(script_url, code)
code = CGI.escapeHTML code
<<-HTML
<div><script src='#{script_url}'></script>
<noscript><pre><code>#{code}</code></pre></noscript></div>
HTML
end
def script_url_for(gist_id, filename)
"https://gist.github.com/#{gist_id}.js?file=#{filename}"
end
def get_gist_url_for(gist, file)
"https://raw.github.com/gist/#{gist}/#{file}"
end
def cache(gist, file, data)
cache_file = get_cache_file_for gist, file
File.open(cache_file, "w") do |io|
io.write data
end
end
def get_cached_gist(gist, file)
return nil if @cache_disabled
cache_file = get_cache_file_for gist, file
File.read cache_file if File.exist? cache_file
end
def get_cache_file_for(gist, file)
bad_chars = /[^a-zA-Z0-9\-_.]/
gist = gist.gsub bad_chars, ''
file = file.gsub bad_chars, ''
md5 = Digest::MD5.hexdigest "#{gist}-#{file}"
File.join @cache_folder, "#{gist}-#{file}-#{md5}.cache"
end
def get_gist_from_web(gist, file)
gist_url = get_gist_url_for gist, file
raw_uri = URI.parse gist_url
proxy = ENV['http_proxy']
if proxy
proxy_uri = URI.parse(proxy)
https = Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port).new raw_uri.host, raw_uri.port
else
https = Net::HTTP.new raw_uri.host, raw_uri.port
end
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new raw_uri.request_uri
data = https.request request
data = data.body
cache gist, file, data unless @cache_disabled
data
end
end
class GistTagNoCache < GistTag
def initialize(tag_name, text, token)
super
@cache_disabled = true
end
end
end
# Liquid::Template.register_tag('gist', Jekyll::GistTag)
# Liquid::Template.register_tag('gistnocache', Jekyll::GistTagNoCache)
#
# Followings are added for Maliq gem.
#
require "pygments"
class GistTagEpub < Jekyll::GistTag
def render(context)
if parts = @text.match(/([\d]*) (.*)/)
gist, file = parts[1].strip, parts[2].strip
code = get_cached_gist(gist, file) || get_gist_from_web(gist, file)
render_pygments(context, code, file)
else
""
end
end
def render_pygments(context, code, file)
opts = { encoding: 'utf-8' }
ext = file[/\.[\w\d]+?$/]
lang = detect_lang(ext)
output = Pygments.highlight(code, :lexer => lang, :options => opts)
output = wrap_with_code_tags(output, lang)
output = context["pygments_prefix"] + output if context["pygments_prefix"]
output = output + context["pygments_suffix"] if context["pygments_suffix"]
output
end
def detect_lang(ext)
Pygments.lexers
.detect { |lang, attrs| attrs[:filenames].include? "*#{ext}" }
.first.downcase
end
def wrap_with_code_tags(code, lang)
code = code.sub(/<pre>/,'<pre><code class="' + lang + '">')
code = code.sub(/<\/pre>/,"</code></pre>")
end
end
Liquid::Template.register_tag('gist', GistTagEpub)
# ------------------------------------
# *** ATTENSION ***
# This file is NOT for Jekyll. It's modified for adapting Maliq(https://github.com/melborne/maliq) gem
# which is a EPUB generator.
# 'gem install pygments.rb' required.
# The original is from Jekyll 0.11.2(https://github.com/mojombo/jekyll/blob/master/lib/jekyll/tags/highlight.rb)
# By: kyoendo(a.k.a melborne) 2012
# Source URL: https://gist.github.com/4134497#file_highlight.rb
# ------------------------------------
#
module Jekyll
class HighlightBlock < Liquid::Block
include Liquid::StandardFilters
# We need a language, but the linenos argument is optional.
SYNTAX = /(\w+)\s?([\w\s=]+)*/
def initialize(tag_name, markup, tokens)
super
if markup =~ SYNTAX
@lang = $1
if defined? $2
tmp_options = {}
$2.split.each do |opt|
key, value = opt.split('=')
if value.nil?
if key == 'linenos'
value = 'inline'
else
value = true
end
end
tmp_options[key] = value
end
tmp_options = tmp_options.to_a.collect { |opt| opt.join('=') }
# additional options to pass to Albino
@options = { 'O' => tmp_options.join(',') }
else
@options = {}
end
else
raise SyntaxError.new("Syntax Error in 'highlight' - Valid syntax: highlight <lang> [linenos]")
end
end
def render(context)
if context.registers[:site].pygments
render_pygments(context, super)
else
render_codehighlighter(context, super)
end
end
def render_pygments(context, code)
output = add_code_tags(Albino.new(code, @lang).to_s(@options), @lang)
output = context["pygments_prefix"] + output if context["pygments_prefix"]
output = output + context["pygments_suffix"] if context["pygments_suffix"]
output
end
def render_codehighlighter(context, code)
#The div is required because RDiscount blows ass
<<-HTML
<div>
<pre><code class='#{@lang}'>#{h(code).strip}</code></pre>
</div>
HTML
end
def add_code_tags(code, lang)
# Add nested <code> tags to code blocks
code = code.sub(/<pre>/,'<pre><code class="' + lang + '">')
code = code.sub(/<\/pre>/,"</code></pre>")
end
end
end
#
# Followings are added for Maliq gem.
#
require 'pygments'
class Jekyll::HighlightBlock
def render(context)
render_pygments(context, super)
end
def render_pygments(context, code)
@options[:encoding] = 'utf-8'
output = add_code_tags(Pygments.highlight(code, :lexer => @lang, :options => @options), @lang)
output = context["pygments_prefix"] + output if context["pygments_prefix"]
output = output + context["pygments_suffix"] if context["pygments_suffix"]
output
end
end
# End of code for Mdpub
Liquid::Template.register_tag('highlight', Jekyll::HighlightBlock)
code { white-space: pre-wrap; }
.highlight {
background-color: #eeeeff;
/*margin: 5px;*/
padding: 0 2px;
border-radius: 5px;
font-size: 80%;
}
/*.highlight { background: #ffffff; }*/
.highlight .c { color: #999988; font-style: italic } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { font-weight: normal } /* Keyword */
.highlight .o { font-weight: normal } /* Operator */
.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #999999; font-weight: normal } /* Comment.Preproc */
.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */
.highlight .cs { color: #999999; font-weight: normal; font-style: italic } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #999999 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: normal } /* Generic.Strong */
.highlight .gu { color: #aaaaaa } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { font-weight: normal } /* Keyword.Constant */
.highlight .kd { font-weight: normal } /* Keyword.Declaration */
.highlight .kp { font-weight: normal } /* Keyword.Pseudo */
.highlight .kr { font-weight: normal } /* Keyword.Reserved */
.highlight .kt { color: #445588; font-weight: normal } /* Keyword.Type */
.highlight .m { color: #009999 } /* Literal.Number */
.highlight .s { color: #d14 } /* Literal.String */
.highlight .na { color: #008080 } /* Name.Attribute */
.highlight .nb { color: #0086B3 } /* Name.Builtin */
.highlight .nc { color: #445588; font-weight: normal } /* Name.Class */
.highlight .no { color: #008080 } /* Name.Constant */
.highlight .ni { color: #800080 } /* Name.Entity */
.highlight .ne { color: #990000; font-weight: normal } /* Name.Exception */
.highlight .nf { color: #990000; font-weight: normal } /* Name.Function */
.highlight .nn { color: #555555 } /* Name.Namespace */
.highlight .nt { color: #000080 } /* Name.Tag */
.highlight .nv { color: #008080 } /* Name.Variable */
.highlight .ow { font-weight: normal } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mf { color: #009999 } /* Literal.Number.Float */
.highlight .mh { color: #009999 } /* Literal.Number.Hex */
.highlight .mi { color: #009999 } /* Literal.Number.Integer */
.highlight .mo { color: #009999 } /* Literal.Number.Oct */
.highlight .sb { color: #d14 } /* Literal.String.Backtick */
.highlight .sc { color: #d14 } /* Literal.String.Char */
.highlight .sd { color: #d14 } /* Literal.String.Doc */
.highlight .s2 { color: #d14 } /* Literal.String.Double */
.highlight .se { color: #d14 } /* Literal.String.Escape */
.highlight .sh { color: #d14 } /* Literal.String.Heredoc */
.highlight .si { color: #d14 } /* Literal.String.Interpol */
.highlight .sx { color: #d14 } /* Literal.String.Other */
.highlight .sr { color: #009926 } /* Literal.String.Regex */
.highlight .s1 { color: #d14 } /* Literal.String.Single */
.highlight .ss { color: #990073 } /* Literal.String.Symbol */
.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #008080 } /* Name.Variable.Class */
.highlight .vg { color: #008080 } /* Name.Variable.Global */
.highlight .vi { color: #008080 } /* Name.Variable.Instance */
.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */
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.