lib/imgkit/imgkit.rb in imgkit-1.5.0 vs lib/imgkit/imgkit.rb in imgkit-1.6.0

- old
+ new

@@ -28,17 +28,18 @@ def initialize(format) super("Unknown Format: #{format}") end end - attr_accessor :source, :stylesheets + attr_accessor :source, :stylesheets, :javascripts attr_reader :options def initialize(url_file_or_html, options = {}) @source = Source.new(url_file_or_html) @stylesheets = [] + @javascripts = [] @options = IMGKit.configuration.default_options.merge(options) @options.merge! find_options_in_meta(url_file_or_html) unless source.url? raise NoExecutableError.new unless File.exists?(IMGKit.configuration.wkhtmltoimage) @@ -100,10 +101,11 @@ end end def to_img(format = nil) append_stylesheets + append_javascripts set_format(format) opts = @source.html? ? {:stdin_data => @source.to_s} : {} result, stderr = capture3(*(command + [opts])) result.force_encoding("ASCII-8BIT") if result.respond_to? :force_encoding @@ -149,17 +151,37 @@ def style_tag_for(stylesheet) "<style>#{stylesheet.respond_to?(:read) ? stylesheet.read : File.read(stylesheet)}</style>" end + def script_tag_for(javascript) + if javascript.respond_to?(:read) + "<script>#{javascript.read}</script>" + else + "<script src=\"#{javascript}\" type=\"text/javascript\"></script>" + end + end + 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.to_s.gsub!(/(<\/head>)/, style_tag_for(stylesheet)+'\1') else @source.to_s.insert(0, style_tag_for(stylesheet)) + end + end + end + + def append_javascripts + raise ImproperSourceError.new('Javascripts may only be added to an HTML source') if javascripts.any? && !@source.html? + + javascripts.each do |javascript| + if @source.to_s.match(/<\/head>/) + @source.to_s.gsub!(/(<\/head>)/, script_tag_for(javascript)+'\1') + else + @source.to_s.insert(0, script_tag_for(javascript)) end end end def normalize_options(options)