Class: WebSnap::Snapper

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

Defined Under Namespace

Classes: ImproperSourceError, NoExecutableError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url_file_or_html, options = {}) ⇒ Snapper

Returns a new instance of Snapper.

Raises:



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/websnap/websnap.rb', line 19

def initialize(url_file_or_html, options={})
  @source = Source.new(url_file_or_html)

  @stylesheets = []

  default_options = {
    :'format' => 'jpg'
  }
  @options = normalize_options(default_options.merge(options))

  raise NoExecutableError.new if wkhtmltoimage.nil? || wkhtmltoimage == ''
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



17
18
19
# File 'lib/websnap/websnap.rb', line 17

def options
  @options
end

#sourceObject

Returns the value of attribute source.



16
17
18
# File 'lib/websnap/websnap.rb', line 16

def source
  @source
end

#stylesheetsObject

Returns the value of attribute stylesheets.



16
17
18
# File 'lib/websnap/websnap.rb', line 16

def stylesheets
  @stylesheets
end

Instance Method Details

#append_stylesheetsObject



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/websnap/websnap.rb', line 63

def append_stylesheets
  raise ImproperSourceError.new('Stylesheets may only be added to an HTML source') if stylesheets.any? && !@source.html?

  stylesheets.each do |stylesheet|
    if @source.to_s.match(/<\/head>/)
      @source = Source.new(@source.to_s.gsub(/(<\/head>)/, style_tag_for(stylesheet)+'\1'))
    else
      @source.to_s.insert(0, style_tag_for(stylesheet))
    end
  end
end

#commandObject



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/websnap/websnap.rb', line 32

def command
  args = [wkhtmltoimage]
  args += @options.to_a.flatten.compact

  if @source.html?
    args << '-' # Get HTML from stdin
  else
    args << @source.to_s
  end

  args << '-' # Read PDF from stdout
  args.join(' ')
end

#style_tag_for(stylesheet) ⇒ Object



75
76
77
# File 'lib/websnap/websnap.rb', line 75

def style_tag_for(stylesheet)
  "<style>#{File.read(stylesheet)}</style>"
end

#to_bytesObject



46
47
48
49
50
51
52
53
# File 'lib/websnap/websnap.rb', line 46

def to_bytes
  img = IO.popen(command, "w+")
  img.puts(@source.to_s) if @source.html?
  img.close_write
  result = img.gets(nil)
  img.close_read
  return result
end

#to_file(path, image_path = nil) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/websnap/websnap.rb', line 55

def to_file(path, image_path=nil)
  append_stylesheets
  path = File.expand_path(path)

  @source = Source.new(@source.to_s.gsub(/images\//, image_path)) unless image_path.nil?
  File.open(path,'w') {|file| file << self.to_bytes}
end