lib/imgkit/imgkit.rb in imgkit-1.2.1 vs lib/imgkit/imgkit.rb in imgkit-1.3.0

- old
+ new

@@ -1,6 +1,7 @@ class IMGKit + KNOWN_FORMATS = [:jpg, :jpeg, :png, :tiff, :tif] class NoExecutableError < StandardError def initialize msg = "No wkhtmltoimage executable found at #{IMGKit.configuration.wkhtmltoimage}\n" msg << ">> Install wkhtmltoimage by hand or try running `imgkit --install-wkhtmltoimage`" @@ -20,10 +21,16 @@ @command = command @stderr = stderr super("Command failed: #{command}: #{stderr}") end end + + class UnknownFormatError < StandardError + def initialize(format) + super("Unknown Format: #{format}") + end + end attr_accessor :source, :stylesheets attr_reader :options def initialize(url_file_or_html, options = {}) @@ -31,18 +38,17 @@ @stylesheets = [] @options = IMGKit.configuration.default_options.merge(options) @options.merge! find_options_in_meta(url_file_or_html) unless source.url? - @options = normalize_options(@options) raise NoExecutableError.new unless File.exists?(IMGKit.configuration.wkhtmltoimage) end def command args = [executable] - args += @options.to_a.flatten.compact + args += normalize_options(@options).to_a.flatten.compact if @source.html? args << '-' # Get HTML from stdin else args << @source.to_s @@ -60,31 +66,43 @@ else default.split('/').last end end - def to_img + def to_img(format = nil) append_stylesheets + set_format(format) result = nil stderr_output = nil Open3.popen3(*command) do |stdin,stdout,stderr| stdin << (@source.to_s) if @source.html? stdin.close result = stdout.gets(nil) + result.force_encoding("ASCII-8BIT") if result.respond_to? :force_encoding stderr_output = stderr.readlines.join stdout.close stderr.close end raise CommandFailedError.new(command.join(' '), stderr_output) unless result return result end def to_file(path) - File.open(path,'w') {|file| file << self.to_img} + format = File.extname(path).gsub(/^\./,'').to_sym + set_format(format) + File.open(path,'w:ASCII-8BIT') {|file| file << self.to_img} end + + def method_missing(name, *args, &block) + if(m = name.to_s.match(/^to_(\w+)/)) + self.send(:to_img, m[1].to_sym) + else + super + end + end protected def find_options_in_meta(body) imgkit_meta_tags(body).inject({}) do |found, tag| @@ -144,7 +162,12 @@ value else value.to_s end end - + + def set_format(format) + format = IMGKit.configuration.default_format unless format + @options.merge!(:format => format.to_s) unless @options[:format] + raise UnknownFormatError.new(format) unless KNOWN_FORMATS.include?(@options[:format].to_sym) + end end