wicked_pdf 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: dd7dae1230ac2e120e6ca1cb235a8f21465df966
4
- data.tar.gz: c66399843e25433bc83ac7970ff392f2a217bf95
3
+ metadata.gz: 9ab8593ac44c5682cf136c152de88154d721bb05
4
+ data.tar.gz: a999e4080b0f2a76c4488058e4ccf24e69cb9d1d
5
5
  SHA512:
6
- metadata.gz: 86a57ed7f58c19916f48c8cfc98074c5e6cb3ca060c1563abbb2c62e2c0eecefeaba635502ece68c870be7b4049422ef7fd326d59507a6a8709d3938def96491
7
- data.tar.gz: e97feccdf135d2e74d2d14e9ba1e944c130ed631c27a2f18c46e5be1f6804ac439e75755a0a3ddeffffe877d33547c07c76f13980b5b42d0eda45f243f98e399
6
+ metadata.gz: 1dc2bb0b82be7d2071dd92648cee85e6ab8f539cce32b3eb92d78ab4758926e156aead56847d6a2663ea9909f79d3f53c37f6b63bf3b01d0d2343efd37b3d3c6
7
+ data.tar.gz: 1595873318fa389a248d5d85203a9fc397a3670d36c3ac73032362bb06f5c38f5c9dbbe78bd5e3c11c233fcfb1ad06b530dbc8ef2bdbe29582b20308605e8158
data/.rubocop.yml ADDED
@@ -0,0 +1,9 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ AllCops:
4
+ Exclude:
5
+ - 'test/dummy/**/*'
6
+
7
+ # I'd like wicked_pdf to keep Ruby 1.8 compatibility for now
8
+ Style/HashSyntax:
9
+ EnforcedStyle: hash_rockets
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,67 @@
1
+ # This configuration was generated by `rubocop --auto-gen-config`
2
+ # on 2015-11-08 18:41:57 -0500 using RuboCop version 0.32.1.
3
+ # The point is for the user to remove these configuration records
4
+ # one by one as the offenses are removed from the code base.
5
+ # Note that changes in the inspected code, or installation of new
6
+ # versions of RuboCop, may require this file to be generated again.
7
+
8
+ # Offense count: 2
9
+ Lint/AmbiguousRegexpLiteral:
10
+ Enabled: false
11
+
12
+ # Offense count: 2
13
+ Lint/HandleExceptions:
14
+ Enabled: false
15
+
16
+ # Offense count: 9
17
+ Metrics/AbcSize:
18
+ Max: 45
19
+
20
+ # Offense count: 2
21
+ Metrics/BlockNesting:
22
+ Max: 4
23
+
24
+ # Offense count: 2
25
+ # Configuration parameters: CountComments.
26
+ Metrics/ClassLength:
27
+ Max: 279
28
+
29
+ # Offense count: 5
30
+ Metrics/CyclomaticComplexity:
31
+ Max: 9
32
+
33
+ # Offense count: 92
34
+ # Configuration parameters: AllowURI, URISchemes.
35
+ Metrics/LineLength:
36
+ Max: 563
37
+
38
+ # Offense count: 14
39
+ # Configuration parameters: CountComments.
40
+ Metrics/MethodLength:
41
+ Max: 30
42
+
43
+ # Offense count: 4
44
+ Metrics/PerceivedComplexity:
45
+ Max: 12
46
+
47
+ # Offense count: 5
48
+ Style/AccessorMethodName:
49
+ Enabled: false
50
+
51
+ # Offense count: 1
52
+ Style/CaseEquality:
53
+ Enabled: false
54
+
55
+ # Offense count: 1
56
+ Style/ClassVars:
57
+ Enabled: false
58
+
59
+ # Offense count: 15
60
+ Style/Documentation:
61
+ Enabled: false
62
+
63
+ # Offense count: 5
64
+ # Cop supports --auto-correct.
65
+ # Configuration parameters: EnforcedStyle, SupportedStyles, AllowInnerSlashes.
66
+ Style/RegexpLiteral:
67
+ Enabled: false
data/.travis.yml CHANGED
@@ -42,6 +42,10 @@ matrix:
42
42
  - rvm: 2.2.0
43
43
  gemfile: gemfiles/rails_edge.gemfile
44
44
  allow_failures:
45
+ - rvm: 1.9.2
46
+ gemfile: gemfiles/3.1.gemfile
47
+ - rvm: 1.9.2
48
+ gemfile: gemfiles/3.2.gemfile
45
49
  - rvm: 1.9.3
46
50
  gemfile: gemfiles/rails_edge.gemfile
47
51
  - rvm: 2.0.0
data/CHANGLOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # Change Log
2
+ All notable changes to this project will be documented in this file.
3
+ This project adheres to [Semantic Versioning](http://semver.org/).
4
+
5
+ ## [1.0.0] - 2015-11-03
6
+ ### Changed
7
+ - Accepted that `WickedPDF` cannot guarantee backwards compatibility with older versions of `wkthmltopdf`, and decided to publish a new version with the MAJOR number incremented, signaling that this may have breaking changes for some people, but providing a path forward for progress. This release number also signals that this is a mature (and relatively stable) project, and should be deemed ready for production (since it has been used in production since ~2009, and downloaded over a *million* times on [RubyGems.org](https://rubygems.org/gems/wicked_pdf)).
8
+ - Stopped attempting to track with version number of `wkhtmltopdf` binary releases (`wkhtmltopdf` v9.x == `WickedPDF` v9.x)
9
+ - Adopted [Semantic Versioning](http://semver.org/) for release numbering
10
+ - Added a CHANGELOG (based on [keepachangelog.com](http://keepachangelog.com/))
11
+ - Misc code tweaks as suggested by [RuboCop](https://github.com/bbatsov/rubocop)
12
+
13
+ ### Added
14
+ - Check version of `wkhtmltopdf` before deciding to pass arguments with or without dashes
15
+ - New arguments and options for the table of contents supported in newer versions of wkhtmltopf: `text_size_shrink`, `level_indentation`, `disable_dotted_lines`, `disable_toc_links`, `xsl_style_sheet`
16
+ - Merge in global options to `pdf_from_html_file` and `pdf_from_string`
17
+ - Add ability to generate pdf from a web resource: `pdf_from_url(url)`
18
+
19
+ ### Removed
20
+ - Explicit dependency on [Rails](https://github.com/rails/rails), since parts of this library may be used without it.
21
+ - Comment out the `:exe_path` option in the generated initalizer by default (since many systems won't have `wkthmltopdf` installed in that specific location)
22
+
23
+ ### Fixed
24
+ - Issues with `file://` paths on Windows-based systems
25
+ - Issues with parsed options/argument ordering on versions of `wkthmltopdf` > 0.9
26
+ - Issues with middleware headers when running Rails app mounted in a subdirectory
27
+ - Issues with options that have a `key: 'value'` syntax when passed to `wkthmltopdf`
28
+ - Issue with `:temp_path` option being deleted from original options hash
29
+ - Issue with header/footer `:content` being deleted after the first page
30
+ - Issues with options being modified during processing (including global config options)
31
+ - Issues with asset helpers recognizing assets specified without a protocol
32
+ - Issues with `url()` references and embedded `data:base64` assests in stylesheets rendered with `wicked_pdf_stylesheet_link_tag`
33
+ - Asset helpers no longer add a file extension if it already is specified with one
34
+
35
+ # Compare Releases
36
+ - [1.0.0...Unreleased](https://github.com/mileszs/wicked_pdf/compare/f0b49fa...HEAD)
37
+ - [1.0.0...1.0.1](https://github.com/mileszs/wicked_pdf/compare/24303d0...f0b49fa)
38
+ - [0.11.0...1.0.0](https://github.com/mileszs/wicked_pdf/compare/968ae69...24303d0)
39
+ - [0.10.2...0.11.0](https://github.com/mileszs/wicked_pdf/compare/076f043...968ae69)
40
+ - [0.10.1...0.10.2](https://github.com/mileszs/wicked_pdf/compare/a920bc9...076f043)
41
+ - [0.10.0...0.10.1](https://github.com/mileszs/wicked_pdf/compare/df67c30...a920bc9)
42
+ - [0.9.10...0.10.0](https://github.com/mileszs/wicked_pdf/compare/9daecee...df67c30)
data/README.md CHANGED
@@ -329,9 +329,11 @@ You may have noticed: this plugin is heavily inspired by the PrinceXML plugin [p
329
329
 
330
330
  1. Fork it
331
331
  2. Create your feature branch (`git checkout -b my-new-feature`)
332
- 3. Commit your changes (`git commit -am 'Add some feature'`)
333
- 4. Push to the branch (`git push origin my-new-feature`)
334
- 5. Create new Pull Request
332
+ 3. Run the test suite and check the output (`rake`)
333
+ 4. Add tests for your feature or fix (please)
334
+ 5. Commit your changes (`git commit -am 'Add some feature'`)
335
+ 6. Push to the branch (`git push origin my-new-feature`)
336
+ 7. Create new Pull Request
335
337
 
336
338
  ### Awesome Peoples
337
339
 
data/Rakefile CHANGED
@@ -5,7 +5,7 @@ require 'rails/version'
5
5
  require 'bundler/gem_tasks'
6
6
 
7
7
  desc 'Default: run unit tests.'
8
- task :default => :setup_and_run_tests
8
+ task :default => [:setup_and_run_tests, :rubocop]
9
9
 
10
10
  desc 'Test the wicked_pdf plugin.'
11
11
  Rake::TestTask.new(:test) do |t|
@@ -15,6 +15,13 @@ Rake::TestTask.new(:test) do |t|
15
15
  t.verbose = true
16
16
  end
17
17
 
18
+ desc 'Run RuboCop'
19
+ task :rubocop do
20
+ return unless RUBY_VERSION > '1.9.2'
21
+ require 'rubocop/rake_task'
22
+ RuboCop::RakeTask.new
23
+ end
24
+
18
25
  desc 'Setup and run all tests'
19
26
  task :setup_and_run_tests do
20
27
  unless File.exist?('test/dummy/config/environment.rb')
@@ -27,12 +34,7 @@ desc 'Generate dummy application for test cases'
27
34
  task :dummy_generate do
28
35
  Rake::Task[:dummy_remove].invoke
29
36
  puts 'Creating dummy application to run tests'
30
-
31
- prefix = ''
32
- if Rails::VERSION::MAJOR != 2
33
- prefix = 'new '
34
- end
35
-
37
+ prefix = (Rails::VERSION::MAJOR == 2) ? '' : 'new '
36
38
  system("rails #{prefix}test/dummy")
37
39
  FileUtils.rm_r Dir.glob('test/dummy/test/*')
38
40
  end
data/lib/wicked_pdf.rb CHANGED
@@ -50,9 +50,8 @@ class WickedPdf
50
50
 
51
51
  def pdf_from_string(string, options = {})
52
52
  options = options.dup
53
- # merge in global config options
54
- options.merge!(WickedPdf.config) {|key, option, config| option}
55
- string_file = WickedPdfTempfile.new("wicked_pdf.html", options[:temp_path])
53
+ options.merge!(WickedPdf.config) { |_key, option, _config| option }
54
+ string_file = WickedPdfTempfile.new('wicked_pdf.html', options[:temp_path])
56
55
  string_file.binmode
57
56
  string_file.write(string)
58
57
  string_file.close
@@ -67,8 +66,8 @@ class WickedPdf
67
66
 
68
67
  def pdf_from_url(url, options = {})
69
68
  # merge in global config options
70
- options.merge!(WickedPdf.config) {|key, option, config| option}
71
- generated_pdf_file = WickedPdfTempfile.new("wicked_pdf_generated_file.pdf", options[:temp_path])
69
+ options.merge!(WickedPdf.config) { |_key, option, _config| option }
70
+ generated_pdf_file = WickedPdfTempfile.new('wicked_pdf_generated_file.pdf', options[:temp_path])
72
71
  command = [@exe_path]
73
72
  command << '-q' unless on_windows? # suppress errors on stdout
74
73
  command += parse_options(options)
@@ -77,10 +76,11 @@ class WickedPdf
77
76
 
78
77
  print_command(command.inspect) if in_development_mode?
79
78
 
80
- err = Open3.popen3(*command) do |stdin, stdout, stderr|
79
+ err = Open3.popen3(*command) do |_stdin, _stdout, stderr|
81
80
  stderr.read
82
81
  end
83
- if return_file = options.delete(:return_file)
82
+ if options[:return_file]
83
+ return_file = options.delete(:return_file)
84
84
  return generated_pdf_file
85
85
  end
86
86
  generated_pdf_file.rewind
@@ -114,7 +114,7 @@ class WickedPdf
114
114
  end
115
115
 
116
116
  def retreive_binary_version
117
- stdin, stdout, stderr = Open3.popen3(@exe_path + ' -V')
117
+ _stdin, stdout, _stderr = Open3.popen3(@exe_path + ' -V')
118
118
  @binary_version = parse_version(stdout.gets(nil))
119
119
  rescue StandardError
120
120
  end
@@ -186,7 +186,7 @@ class WickedPdf
186
186
  if options[o].blank?
187
187
  []
188
188
  else
189
- make_option("#{prefix.blank? ? '' : prefix + '-'}#{o.to_s}",
189
+ make_option("#{prefix.blank? ? '' : prefix + '-'}#{o}",
190
190
  options[o],
191
191
  type)
192
192
  end
@@ -196,22 +196,21 @@ class WickedPdf
196
196
  def parse_header_footer(options)
197
197
  r = []
198
198
  [:header, :footer].collect do |hf|
199
- unless options[hf].blank?
200
- opt_hf = options[hf]
201
- r += make_options(opt_hf, [:center, :font_name, :left, :right], "#{hf.to_s}")
202
- r += make_options(opt_hf, [:font_size, :spacing], "#{hf.to_s}", :numeric)
203
- r += make_options(opt_hf, [:line], "#{hf.to_s}", :boolean)
204
- if options[hf] && options[hf][:content]
205
- @hf_tempfiles = [] unless defined?(@hf_tempfiles)
206
- @hf_tempfiles.push(tf = WickedPdfTempfile.new("wicked_#{hf}_pdf.html"))
207
- tf.write options[hf][:content]
208
- tf.flush
209
- options[hf][:html] = {}
210
- options[hf][:html][:url] = "file:///#{tf.path}"
211
- end
212
- unless opt_hf[:html].blank?
213
- r += make_option("#{hf.to_s}-html", opt_hf[:html][:url]) unless opt_hf[:html][:url].blank?
214
- end
199
+ next if options[hf].blank?
200
+ opt_hf = options[hf]
201
+ r += make_options(opt_hf, [:center, :font_name, :left, :right], "#{hf}")
202
+ r += make_options(opt_hf, [:font_size, :spacing], "#{hf}", :numeric)
203
+ r += make_options(opt_hf, [:line], "#{hf}", :boolean)
204
+ if options[hf] && options[hf][:content]
205
+ @hf_tempfiles = [] unless defined?(@hf_tempfiles)
206
+ @hf_tempfiles.push(tf = WickedPdfTempfile.new("wicked_#{hf}_pdf.html"))
207
+ tf.write options[hf][:content]
208
+ tf.flush
209
+ options[hf][:html] = {}
210
+ options[hf][:html][:url] = "file:///#{tf.path}"
211
+ end
212
+ unless opt_hf[:html].blank?
213
+ r += make_option("#{hf}-html", opt_hf[:html][:url]) unless opt_hf[:html][:url].blank?
215
214
  end
216
215
  end unless options.blank?
217
216
  r
@@ -1,6 +1,5 @@
1
1
  class WickedPdf
2
2
  class Middleware
3
-
4
3
  def initialize(app, options = {}, conditions = {})
5
4
  @app = app
6
5
  @options = (WickedPdf.config || {}).merge(options)
@@ -89,6 +88,5 @@ class WickedPdf
89
88
  def concat(accepts, type)
90
89
  (accepts || '').split(',').unshift(type).compact.join(',')
91
90
  end
92
-
93
91
  end
94
92
  end
@@ -43,15 +43,13 @@ module PdfHelper
43
43
 
44
44
  def set_basic_auth(options = {})
45
45
  options[:basic_auth] ||= WickedPdf.config.fetch(:basic_auth) { false }
46
- if options[:basic_auth] && request.env['HTTP_AUTHORIZATION']
47
- request.env['HTTP_AUTHORIZATION'].split(' ').last
48
- end
46
+ return unless options[:basic_auth] && request.env['HTTP_AUTHORIZATION']
47
+ request.env['HTTP_AUTHORIZATION'].split(' ').last
49
48
  end
50
49
 
51
50
  def clean_temp_files
52
- if defined?(@hf_tempfiles)
53
- @hf_tempfiles.each { |tf| tf.close! }
54
- end
51
+ return unless defined?(@hf_tempfiles)
52
+ @hf_tempfiles.each(&:close!)
55
53
  end
56
54
 
57
55
  def make_pdf(options = {})
@@ -66,8 +64,8 @@ module PdfHelper
66
64
 
67
65
  def make_and_send_pdf(pdf_name, options = {})
68
66
  options[:wkhtmltopdf] ||= nil
69
- options[:layout] ||= false
70
- options[:template] ||= File.join(controller_path, action_name)
67
+ options[:layout] ||= false
68
+ options[:template] ||= File.join(controller_path, action_name)
71
69
  options[:disposition] ||= 'inline'
72
70
  if options[:show_as_html]
73
71
  render_opts = { :template => options[:template], :layout => options[:layout], :formats => options[:formats], :handlers => options[:handlers], :content_type => 'text/html' }
@@ -85,17 +83,16 @@ module PdfHelper
85
83
  # to temp files and return a new options hash including the URLs to these files.
86
84
  def prerender_header_and_footer(options)
87
85
  [:header, :footer].each do |hf|
88
- if options[hf] && options[hf][:html] && options[hf][:html][:template]
89
- @hf_tempfiles = [] unless defined?(@hf_tempfiles)
90
- @hf_tempfiles.push(tf = WickedPdfTempfile.new("wicked_#{hf}_pdf.html"))
91
- options[hf][:html][:layout] ||= options[:layout]
92
- render_opts = { :template => options[hf][:html][:template], :layout => options[hf][:html][:layout], :formats => options[hf][:html][:formats], :handlers => options[hf][:html][:handlers] }
93
- render_opts.merge!(:locals => options[hf][:html][:locals]) if options[hf][:html][:locals]
94
- render_opts.merge!(:file => options[hf][:html][:file]) if options[:file]
95
- tf.write render_to_string(render_opts)
96
- tf.flush
97
- options[hf][:html][:url] = "file:///#{tf.path}"
98
- end
86
+ next unless options[hf] && options[hf][:html] && options[hf][:html][:template]
87
+ @hf_tempfiles = [] unless defined?(@hf_tempfiles)
88
+ @hf_tempfiles.push(tf = WickedPdfTempfile.new("wicked_#{hf}_pdf.html"))
89
+ options[hf][:html][:layout] ||= options[:layout]
90
+ render_opts = { :template => options[hf][:html][:template], :layout => options[hf][:html][:layout], :formats => options[hf][:html][:formats], :handlers => options[hf][:html][:handlers] }
91
+ render_opts.merge!(:locals => options[hf][:html][:locals]) if options[hf][:html][:locals]
92
+ render_opts.merge!(:file => options[hf][:html][:file]) if options[:file]
93
+ tf.write render_to_string(render_opts)
94
+ tf.flush
95
+ options[hf][:html][:url] = "file:///#{tf.path}"
99
96
  end
100
97
  options
101
98
  end
@@ -1,12 +1,13 @@
1
1
  require 'wicked_pdf/pdf_helper'
2
2
  require 'wicked_pdf/wicked_pdf_helper'
3
+ require 'wicked_pdf/wicked_pdf_helper/assets'
3
4
 
4
5
  if defined?(Rails)
5
6
 
6
7
  if Rails::VERSION::MAJOR == 3
7
8
 
8
9
  class WickedRailtie < Rails::Railtie
9
- initializer 'wicked_pdf.register' do |app|
10
+ initializer 'wicked_pdf.register' do |_app|
10
11
  ActionController::Base.send :include, PdfHelper
11
12
  if Rails::VERSION::MINOR > 0 && Rails.configuration.assets.enabled
12
13
  ActionView::Base.send :include, WickedPdfHelper::Assets
@@ -28,7 +29,7 @@ if defined?(Rails)
28
29
  else
29
30
 
30
31
  class WickedRailtie < Rails::Railtie
31
- initializer 'wicked_pdf.register' do |app|
32
+ initializer 'wicked_pdf.register' do |_app|
32
33
  ActionController::Base.send :include, PdfHelper
33
34
  ActionView::Base.send :include, WickedPdfHelper::Assets
34
35
  end
@@ -3,7 +3,7 @@ require 'tempfile'
3
3
  class WickedPdfTempfile < Tempfile
4
4
  # ensures the Tempfile's filename always keeps its extension
5
5
  def initialize(filename, temp_dir = nil)
6
- temp_dir ||= Dir.tmpdir
6
+ temp_dir ||= Dir.tmpdir
7
7
  extension = File.extname(filename)
8
8
  basename = File.basename(filename, extension)
9
9
  super([basename, extension], temp_dir)
@@ -1,3 +1,3 @@
1
1
  class WickedPdf
2
- VERSION = '1.0.0'
2
+ VERSION = '1.0.1'
3
3
  end
@@ -1,20 +1,18 @@
1
- require 'open-uri'
2
-
3
1
  module WickedPdfHelper
4
2
  def self.root_path
5
3
  String === Rails.root ? Pathname.new(Rails.root) : Rails.root
6
4
  end
7
5
 
8
6
  def self.add_extension(filename, extension)
9
- (filename.to_s.split(".").include?(extension) ? filename : "#{filename}.#{extension}")
7
+ filename.to_s.split('.').include?(extension) ? filename : "#{filename}.#{extension}"
10
8
  end
11
9
 
12
10
  def wicked_pdf_stylesheet_link_tag(*sources)
13
11
  css_dir = WickedPdfHelper.root_path.join('public', 'stylesheets')
14
- css_text = sources.collect { |source|
12
+ css_text = sources.collect do |source|
15
13
  source = WickedPdfHelper.add_extension(source, 'css')
16
14
  "<style type='text/css'>#{File.read(css_dir.join(source))}</style>"
17
- }.join("\n")
15
+ end.join("\n")
18
16
  css_text.respond_to?(:html_safe) ? css_text.html_safe : css_text
19
17
  end
20
18
 
@@ -32,108 +30,4 @@ module WickedPdfHelper
32
30
  js_text = sources.collect { |source| wicked_pdf_javascript_src_tag(source, {}) }.join("\n")
33
31
  js_text.respond_to?(:html_safe) ? js_text.html_safe : js_text
34
32
  end
35
-
36
- module Assets
37
- ASSET_URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/
38
-
39
- def wicked_pdf_stylesheet_link_tag(*sources)
40
- stylesheet_contents = sources.collect do |source|
41
- source = WickedPdfHelper.add_extension(source, 'css')
42
- "<style type='text/css'>#{read_asset(source)}</style>"
43
- end.join("\n")
44
-
45
- stylesheet_contents.gsub(ASSET_URL_REGEX) do
46
- if Regexp.last_match[1].starts_with?('data:')
47
- "url(#{Regexp.last_match[1]})"
48
- else
49
- "url(#{wicked_pdf_asset_path(Regexp.last_match[1])})"
50
- end
51
- end.html_safe
52
- end
53
-
54
- def wicked_pdf_image_tag(img, options = {})
55
- image_tag wicked_pdf_asset_path(img), options
56
- end
57
-
58
- def wicked_pdf_javascript_src_tag(jsfile, options = {})
59
- jsfile = WickedPdfHelper.add_extension(jsfile, 'js')
60
- javascript_include_tag wicked_pdf_asset_path(jsfile), options
61
- end
62
-
63
- def wicked_pdf_javascript_include_tag(*sources)
64
- sources.collect { |source|
65
- source = WickedPdfHelper.add_extension(source, 'js')
66
- "<script type='text/javascript'>#{read_asset(source)}</script>"
67
- }.join("\n").html_safe
68
- end
69
-
70
- def wicked_pdf_asset_path(asset)
71
- if (pathname = asset_pathname(asset).to_s) =~ URI_REGEXP
72
- pathname
73
- else
74
- "file:///#{pathname}"
75
- end
76
- end
77
-
78
- private
79
-
80
- # borrowed from actionpack/lib/action_view/helpers/asset_url_helper.rb
81
- URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}
82
-
83
- def asset_pathname(source)
84
- if precompiled_asset?(source)
85
- if (pathname = set_protocol(asset_path(source))) =~ URI_REGEXP
86
- # asset_path returns an absolute URL using asset_host if asset_host is set
87
- pathname
88
- else
89
- File.join(Rails.public_path, asset_path(source).sub(/\A#{Rails.application.config.action_controller.relative_url_root}/, ''))
90
- end
91
- else
92
- Rails.application.assets.find_asset(source).pathname
93
- end
94
- end
95
-
96
- # will prepend a http or default_protocol to a protocol relative URL
97
- # or when no protcol is set.
98
- def set_protocol(source)
99
- protocol = WickedPdf.config[:default_protocol] || 'http'
100
- if source[0, 2] == '//'
101
- source = [protocol, ':', source].join
102
- elsif source[0] != '/' && !source[0, 8].include?('://')
103
- source = [protocol, '://', source].join
104
- end
105
- source
106
- end
107
-
108
- def precompiled_asset?(source)
109
- Rails.configuration.assets.compile == false || source.to_s[0] == '/'
110
- end
111
-
112
- def read_asset(source)
113
- if precompiled_asset?(source)
114
- if set_protocol(asset_path(source)) =~ URI_REGEXP
115
- read_from_uri(source)
116
- else
117
- IO.read(asset_pathname(source))
118
- end
119
- else
120
- Rails.application.assets.find_asset(source).to_s
121
- end
122
- end
123
-
124
- def read_from_uri(source)
125
- encoding = ':UTF-8' if RUBY_VERSION > '1.8'
126
- asset = open(asset_pathname(source), "r#{encoding}") { |f| f.read }
127
- asset = gzip(asset) if WickedPdf.config[:expect_gzipped_remote_assets]
128
- asset
129
- end
130
-
131
- def gzip(asset)
132
- stringified_asset = StringIO.new(asset)
133
- gzipper = Zlib::GzipReader.new(stringified_asset)
134
- gzipped_asset = gzipper.read
135
- rescue Zlib::GzipFile::Error
136
- end
137
-
138
- end
139
33
  end
@@ -0,0 +1,120 @@
1
+ require 'open-uri'
2
+
3
+ module WickedPdfHelper
4
+ module Assets
5
+ ASSET_URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/
6
+
7
+ def wicked_pdf_asset_base64(path)
8
+ asset = Rails.application.assets.find_asset(path)
9
+ throw "Could not find asset '#{path}'" if asset.nil?
10
+ base64 = Base64.encode64(asset.to_s).gsub(/\s+/, '')
11
+ "data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
12
+ end
13
+
14
+ def wicked_pdf_stylesheet_link_tag(*sources)
15
+ stylesheet_contents = sources.collect do |source|
16
+ source = WickedPdfHelper.add_extension(source, 'css')
17
+ "<style type='text/css'>#{read_asset(source)}</style>"
18
+ end.join("\n")
19
+
20
+ stylesheet_contents.gsub(ASSET_URL_REGEX) do
21
+ if Regexp.last_match[1].starts_with?('data:')
22
+ "url(#{Regexp.last_match[1]})"
23
+ else
24
+ asset = Regexp.last_match[1]
25
+ if asset_exists?(asset)
26
+ "url(#{wicked_pdf_asset_path(asset)})"
27
+ end
28
+ end
29
+ end.html_safe
30
+ end
31
+
32
+ def wicked_pdf_image_tag(img, options = {})
33
+ image_tag wicked_pdf_asset_path(img), options
34
+ end
35
+
36
+ def wicked_pdf_javascript_src_tag(jsfile, options = {})
37
+ jsfile = WickedPdfHelper.add_extension(jsfile, 'js')
38
+ javascript_include_tag wicked_pdf_asset_path(jsfile), options
39
+ end
40
+
41
+ def wicked_pdf_javascript_include_tag(*sources)
42
+ sources.collect do |source|
43
+ source = WickedPdfHelper.add_extension(source, 'js')
44
+ "<script type='text/javascript'>#{read_asset(source)}</script>"
45
+ end.join("\n").html_safe
46
+ end
47
+
48
+ def wicked_pdf_asset_path(asset)
49
+ if (pathname = asset_pathname(asset).to_s) =~ URI_REGEXP
50
+ pathname
51
+ else
52
+ "file:///#{pathname}"
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ # borrowed from actionpack/lib/action_view/helpers/asset_url_helper.rb
59
+ URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}
60
+
61
+ def asset_pathname(source)
62
+ if precompiled_asset?(source)
63
+ if (pathname = set_protocol(asset_path(source))) =~ URI_REGEXP
64
+ # asset_path returns an absolute URL using asset_host if asset_host is set
65
+ pathname
66
+ else
67
+ File.join(Rails.public_path, asset_path(source).sub(/\A#{Rails.application.config.action_controller.relative_url_root}/, ''))
68
+ end
69
+ else
70
+ Rails.application.assets.find_asset(source).pathname
71
+ end
72
+ end
73
+
74
+ # will prepend a http or default_protocol to a protocol relative URL
75
+ # or when no protcol is set.
76
+ def set_protocol(source)
77
+ protocol = WickedPdf.config[:default_protocol] || 'http'
78
+ if source[0, 2] == '//'
79
+ source = [protocol, ':', source].join
80
+ elsif source[0] != '/' && !source[0, 8].include?('://')
81
+ source = [protocol, '://', source].join
82
+ end
83
+ source
84
+ end
85
+
86
+ def precompiled_asset?(source)
87
+ Rails.configuration.assets.compile == false || source.to_s[0] == '/'
88
+ end
89
+
90
+ def read_asset(source)
91
+ if precompiled_asset?(source)
92
+ if set_protocol(asset_path(source)) =~ URI_REGEXP
93
+ read_from_uri(source)
94
+ elsif asset_exists?(source)
95
+ IO.read(asset_pathname(source))
96
+ end
97
+ else
98
+ Rails.application.assets.find_asset(source).to_s
99
+ end
100
+ end
101
+
102
+ def read_from_uri(source)
103
+ encoding = ':UTF-8' if RUBY_VERSION > '1.8'
104
+ asset = open(asset_pathname(source), "r#{encoding}") { |f| f.read }
105
+ asset = gzip(asset) if WickedPdf.config[:expect_gzipped_remote_assets]
106
+ asset
107
+ end
108
+
109
+ def gzip(asset)
110
+ stringified_asset = StringIO.new(asset)
111
+ gzipper = Zlib::GzipReader.new(stringified_asset)
112
+ gzipper.read
113
+ rescue Zlib::GzipFile::Error
114
+ end
115
+
116
+ def asset_exists?(source)
117
+ Rails.application.assets.find_asset(source).present?
118
+ end
119
+ end
120
+ end
@@ -2,10 +2,16 @@ require 'test_helper'
2
2
  require 'action_view/test_case'
3
3
 
4
4
  class WickedPdfHelperAssetsTest < ActionView::TestCase
5
-
6
5
  include WickedPdfHelper::Assets
7
6
 
8
7
  if Rails::VERSION::MAJOR > 3 || (Rails::VERSION::MAJOR == 3 && Rails::VERSION::MINOR > 0)
8
+ test 'wicked_pdf_asset_base64 returns a base64 encoded asset' do
9
+ source = File.new('test/fixtures/wicked.css', 'r')
10
+ destination = Rails.root.join('app', 'assets', 'stylesheets', 'wicked.css')
11
+ File.open(destination, 'w') { |f| f.write(source) }
12
+ assert_match /data:text\/css;base64,.+/, wicked_pdf_asset_base64('wicked.css')
13
+ end
14
+
9
15
  test 'wicked_pdf_asset_path should return a url when assets are served by an asset server' do
10
16
  expects(:asset_pathname => 'http://assets.domain.com/dummy.png')
11
17
  assert_equal 'http://assets.domain.com/dummy.png', wicked_pdf_asset_path('dummy.png')
@@ -95,18 +95,18 @@ class WickedPdfTest < ActiveSupport::TestCase
95
95
 
96
96
  [:header, :footer].each do |hf|
97
97
  [:center, :font_name, :left, :right].each do |o|
98
- assert_equal "--#{hf.to_s}-#{o.to_s.gsub('_', '-')} header_footer",
98
+ assert_equal "--#{hf}-#{o.to_s.gsub('_', '-')} header_footer",
99
99
  wp.get_parsed_options(hf => { o => 'header_footer' }).strip
100
100
  end
101
101
 
102
102
  [:font_size, :spacing].each do |o|
103
- assert_equal "--#{hf.to_s}-#{o.to_s.gsub('_', '-')} 12",
103
+ assert_equal "--#{hf}-#{o.to_s.gsub('_', '-')} 12",
104
104
  wp.get_parsed_options(hf => { o => '12' }).strip
105
105
  end
106
106
 
107
- assert_equal "--#{hf.to_s}-line",
107
+ assert_equal "--#{hf}-line",
108
108
  wp.get_parsed_options(hf => { :line => true }).strip
109
- assert_equal "--#{hf.to_s}-html http://www.abc.com",
109
+ assert_equal "--#{hf}-html http://www.abc.com",
110
110
  wp.get_parsed_options(hf => { :html => { :url => 'http://www.abc.com' } }).strip
111
111
  end
112
112
  end
@@ -120,7 +120,8 @@ class WickedPdfTest < ActiveSupport::TestCase
120
120
  wp.get_parsed_options(:toc => { o => 'toc' }).strip
121
121
  end
122
122
 
123
- [:depth, :header_fs, :l1_font_size, :l2_font_size, :l3_font_size, :l4_font_size,
123
+ [
124
+ :depth, :header_fs, :l1_font_size, :l2_font_size, :l3_font_size, :l4_font_size,
124
125
  :l5_font_size, :l6_font_size, :l7_font_size, :l1_indentation, :l2_indentation,
125
126
  :l3_indentation, :l4_indentation, :l5_indentation, :l6_indentation, :l7_indentation
126
127
  ].each do |o|
@@ -145,7 +146,7 @@ class WickedPdfTest < ActiveSupport::TestCase
145
146
  wp = WickedPdf.new
146
147
 
147
148
  [:top, :bottom, :left, :right].each do |o|
148
- assert_equal "--margin-#{o.to_s} 12", wp.get_parsed_options(:margin => { o => '12' }).strip
149
+ assert_equal "--margin-#{o} 12", wp.get_parsed_options(:margin => { o => '12' }).strip
149
150
  end
150
151
  end
151
152
 
@@ -155,14 +156,15 @@ class WickedPdfTest < ActiveSupport::TestCase
155
156
 
156
157
  pathname = Rails.root.join('app', 'views', 'pdf', 'file.html')
157
158
  assert_equal "#{cover_option} http://example.org", wp.get_parsed_options(:cover => 'http://example.org').strip, 'URL'
158
- assert_equal "#{cover_option} #{pathname.to_s}", wp.get_parsed_options(:cover => pathname).strip, 'Pathname'
159
+ assert_equal "#{cover_option} #{pathname}", wp.get_parsed_options(:cover => pathname).strip, 'Pathname'
159
160
  assert_match /#{cover_option} .+wicked_cover_pdf.+\.html/, wp.get_parsed_options(:cover => '<html><body>HELLO</body></html>').strip, 'HTML'
160
161
  end
161
162
 
162
163
  test 'should parse other options' do
163
164
  wp = WickedPdf.new
164
165
 
165
- [:orientation, :page_size, :proxy, :username, :password, :dpi,
166
+ [
167
+ :orientation, :page_size, :proxy, :username, :password, :dpi,
166
168
  :encoding, :user_style_sheet
167
169
  ].each do |o|
168
170
  assert_equal "--#{o.to_s.gsub('_', '-')} opts", wp.get_parsed_options(o => 'opts').strip
@@ -179,7 +181,8 @@ class WickedPdfTest < ActiveSupport::TestCase
179
181
  assert_equal "--#{o.to_s.gsub('_', '-')} 5", wp.get_parsed_options(o => 5).strip
180
182
  end
181
183
 
182
- [:book, :default_header, :disable_javascript, :grayscale, :lowquality,
184
+ [
185
+ :book, :default_header, :disable_javascript, :grayscale, :lowquality,
183
186
  :enable_plugins, :disable_internal_links, :disable_external_links,
184
187
  :print_media_type, :disable_smart_shrinking, :use_xserver, :no_background
185
188
  ].each do |o|
data/wicked_pdf.gemspec CHANGED
@@ -21,6 +21,7 @@ Gem::Specification.new do |spec|
21
21
  spec.add_development_dependency 'rails'
22
22
  spec.add_development_dependency 'bundler', '~> 1.3'
23
23
  spec.add_development_dependency 'rake'
24
+ spec.add_development_dependency 'rubocop' if RUBY_VERSION > '1.9.2'
24
25
  spec.add_development_dependency 'sqlite3'
25
26
  spec.add_development_dependency 'mocha'
26
27
  spec.add_development_dependency 'test-unit'
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: wicked_pdf
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Miles Z. Sterrett
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-11-04 00:00:00.000000000 Z
11
+ date: 2015-11-19 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -52,6 +52,20 @@ dependencies:
52
52
  - - ">="
53
53
  - !ruby/object:Gem::Version
54
54
  version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rubocop
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
55
69
  - !ruby/object:Gem::Dependency
56
70
  name: sqlite3
57
71
  requirement: !ruby/object:Gem::Requirement
@@ -104,7 +118,10 @@ extensions: []
104
118
  extra_rdoc_files: []
105
119
  files:
106
120
  - ".gitignore"
121
+ - ".rubocop.yml"
122
+ - ".rubocop_todo.yml"
107
123
  - ".travis.yml"
124
+ - CHANGLOG.md
108
125
  - Gemfile
109
126
  - LICENSE.txt
110
127
  - README.md
@@ -128,6 +145,7 @@ files:
128
145
  - lib/wicked_pdf/tempfile.rb
129
146
  - lib/wicked_pdf/version.rb
130
147
  - lib/wicked_pdf/wicked_pdf_helper.rb
148
+ - lib/wicked_pdf/wicked_pdf_helper/assets.rb
131
149
  - test/fixtures/document_with_long_line.html
132
150
  - test/fixtures/wicked.css
133
151
  - test/functional/pdf_helper_test.rb