Class: Grandfather::Combine

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

Instance Method Summary collapse

Constructor Details

#initialize(files, config) ⇒ Combine

Returns a new instance of Combine.



8
9
10
11
12
13
# File 'lib/grandfather/combine.rb', line 8

def initialize(files, config)
  @files, @config = files, config

  @stylesheets = []
  @wkhtmltopdf = Wkhtmltopdf.new @config.wkhtmltopdf_parameters
end

Instance Method Details

#add_head(html) ⇒ Object



35
36
37
# File 'lib/grandfather/combine.rb', line 35

def add_head(html)
  html.insert(0, "\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n</head>\n")
end

#append_stylesheets(html) ⇒ Object



45
46
47
48
49
# File 'lib/grandfather/combine.rb', line 45

def append_stylesheets(html)
  @stylesheets.each do |stylesheet|
    html.insert(0, style_tag_for(stylesheet))
  end
end

#combine!Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/grandfather/combine.rb', line 15

def combine!
  merged_contents = []
  @files.each do |file|
    markup = Renderer.new file
    merged_contents << markup.render
    merged_contents << "<div class=\"page-break\"></div>"
  end

  unless merged_contents.empty?
    output_pdf(merged_contents.join, nil)
  end
end

#load_stylesheetsObject



39
40
41
42
43
# File 'lib/grandfather/combine.rb', line 39

def load_stylesheets
  style = ::File.expand_path("../../../config/style.css", __FILE__)
  @stylesheets << style
  @stylesheets << stylesheet if ::File.exists?(stylesheet)
end

#output_dirObject



59
60
61
62
63
# File 'lib/grandfather/combine.rb', line 59

def output_dir
  output_dir = @config.output_dir.nil? ? Dir.getwd : @config.output_dir
  FileUtils.mkdir_p*output_dir unless ::File.directory?(output_dir)
  output_dir
end

#output_file(file = nil) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/grandfather/combine.rb', line 65

def output_file(file = nil)
  if file
    output_filename = file.name
    if !@config.output_filename.nil? && @files.length == 1
      output_filename = @config.output_filename
    end
  else
    output_filename = "default"
  end

  ::File.join(output_dir, "#{output_filename}.pdf")
end

#output_pdf(html, filename) ⇒ Object



28
29
30
31
32
33
# File 'lib/grandfather/combine.rb', line 28

def output_pdf(html, filename)
  load_stylesheets
  append_stylesheets html
  add_head html
  @wkhtmltopdf.output_pdf html, output_file(filename)
end

#style_tag_for(stylesheet) ⇒ Object



51
52
53
# File 'lib/grandfather/combine.rb', line 51

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

#stylesheetObject



55
56
57
# File 'lib/grandfather/combine.rb', line 55

def stylesheet
  @config.stylesheet.nil? ? 'default.css' : @config.stylesheet
end