Class: Albino

Inherits:
Object
  • Object
show all
Defined in:
lib/vendor/albino.rb

Constant Summary collapse

WEB_API_ROOT =
URI.parse('http://pygments.appspot.com/')
@@bin =
(Rails.env) && Rails.env.development?) ? 'pygmentize' : '/usr/bin/pygmentize'
@@use_web_api =
false

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, lexer = :text, format = :html) ⇒ Albino

Returns a new instance of Albino.



88
89
90
91
92
# File 'lib/vendor/albino.rb', line 88

def initialize(target, lexer = :text, format = :html)
  @target  = File.exists?(target) ? File.read(target) : target rescue target
  @options = { :l => lexer, :f => format }
  @web_options = {'lang' => lexer.to_s}
end

Class Method Details

.bin=(path) ⇒ Object



72
73
74
# File 'lib/vendor/albino.rb', line 72

def self.bin=(path)
  @@bin = path
end

.colorize(*args) ⇒ Object



84
85
86
# File 'lib/vendor/albino.rb', line 84

def self.colorize(*args)
  new(*args).colorize
end

.highlight_code(html) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/vendor/albino.rb', line 56

def self.highlight_code(html)
  doc = Nokogiri::HTML(html)
  doc.search('div.code').each do |div|
    lexer = div['rel'] || :ruby
    lexted_text = Albino.new(div.text, lexer).to_s
    highlighted = Nokogiri::HTML(lexted_text).at('div')
    klasses = highlighted['class'].split(/\s+/)
    klasses << lexer
    klasses << 'code'
    klasses << 'highlight'
    highlighted['class'] = klasses.join(' ')
    div.replace highlighted
  end
  doc.search('body > *').to_html
end

.use_web_api=(value) ⇒ Object



80
81
82
# File 'lib/vendor/albino.rb', line 80

def self.use_web_api=(value)
  @@use_web_api = !!value
end

.use_web_api?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/vendor/albino.rb', line 76

def self.use_web_api?
  @@use_web_api
end

Instance Method Details

#colorize(options = {}) ⇒ Object Also known as: to_s



109
110
111
112
113
114
115
# File 'lib/vendor/albino.rb', line 109

def colorize(options = {})
  if self.class.use_web_api?
    highlight_via_api
  else
    execute @@bin + convert_options(options)
  end
end

#convert_options(options = {}) ⇒ Object



118
119
120
121
122
# File 'lib/vendor/albino.rb', line 118

def convert_options(options = {})
  @options.merge(options).inject('') do |string, (flag, value)|
    string + " -#{flag} #{value}"
  end
end

#execute(command) ⇒ Object



94
95
96
97
98
99
100
101
102
# File 'lib/vendor/albino.rb', line 94

def execute(command)
  tmp = Tempfile.new("albino")
  tmp.write @target
  tmp.close
  command = [command, tmp.path].join(" ")
  %x(#{command}).strip
ensure
  tmp.unlink if tmp
end

#highlight_via_apiObject



104
105
106
107
# File 'lib/vendor/albino.rb', line 104

def highlight_via_api
  request = Net::HTTP.post_form(WEB_API_ROOT, @web_options.merge('code' => @target))
  request.body
end