Sha256: f03a74cd290ccad1d449f5ce832a8f24e392486f79f7b3e75c3180fa125d94a8

Contents?: true

Size: 1.89 KB

Versions: 9

Compression:

Stored size: 1.89 KB

Contents

module Spontaneous::Field
  class Image
    class Size
      include Spontaneous::Media::Image::Renderable

      attr_reader :path

      def initialize(input, name, options, process)
        @input, @name, @process = input, name, process
        @options = {:optimize => true}.merge(options)
      end

      def generate
        tempfile do |tempfile|
          convert(tempfile)
          file = @input.rename(filename)
          file.copy(tempfile)
          serialize(file)
        end
      end

      def serialize(file)
        values = file.serialize
        path = values.delete(:path)
        src  = values.delete(:url)
        image = Spontaneous::Media::Image.new(file.source)
        values.update(image.attributes).update(:src => src)
      end

      def convert(tempfile)
        processor = Spontaneous::Media::Image::Processor.new(path, tempfile.path)
        processor.apply(process)
        optimize(tempfile) if @options[:optimize]
      end

      def optimize(tempfile)
        Spontaneous::Media::Image::Optimizer.run(tempfile.path)
      end

      def process
        @process || Proc.new {  }
      end

      def path
        @input.source
      end

      def extname
        (format = @options[:format]) ? ".#{format}" : @input.extname
      end

      def tempfile(&block)
        dir  = Dir.mktmpdir
        name = "#{@name}#{extname}"
        path = ::File.join(dir, name)
        ::File.open(path, "w+b") do |file|
          block.call file
        end
      ensure
        FileUtils.rm_rf(dir) rescue nil
      end

      def filename
        original_filename = @input.filename
        parts = original_filename.split('.')
        base = parts[0..-2].join('.')
        size = @name == :original ? "" : ".#{@name}"
        "#{base}#{size}#{extname}"
      end

      def inspect
        %(#<Spontaneous::Field::Image::Size name=:#{@name} options=#{@options.inspect}>)
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
spontaneous-0.2.0.beta10 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta9 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta8 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta7 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta6 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta5 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta4 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta3 lib/spontaneous/field/image/size.rb
spontaneous-0.2.0.beta2 lib/spontaneous/field/image/size.rb