Sha256: 889c4b78114e1014e8f7a86bb0354c3c99506cbe66d2b0c3c43ffa6f0596c9e5

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

# CleanRoom
module Picturefill
  class Context
    IMAGE = Struct.new(:src, :media, :options)

    def initialize(&blk)
      @self_before_instance_eval = eval("self", blk.binding)
      instance_eval(&blk)
    end

    def each(&blk)
      (@images ||= []).each(&blk)
    end

  private

    # Usage: image("small.jpg", :ratio => 2, :min => 400, :media => 'custom')
    #        image("small.jpg", '(min-width: 400px)')
    def image(src, options = {})
      media = extract_media!(options)
      (@images ||= []) << IMAGE.new(src, media, options)

      # Do not render anything here!
      return ""
    end

    # Returns: A string
    # Example: "(min-width: 400px) and (min-device-pixel-ratio: 2.0)"
    def extract_media!(options)
      case options
      when String
        options
      when Hash
        min   = options.delete :min
        ratio = options.delete :ratio
        media = options.delete :media

        min   = "(min-width: #{400}px)" if min
        ratio = case ratio
                when Float
                  "(min-device-pixel-ratio: #{ratio})"
                when Integer
                  "(min-device-pixel-ratio: %.1f)" % ratio
                when nil
                else
                  ArgumentError
                end
        media = "(#{media})" if media

        [min, ratio, media].select { |e| !e.nil? }.join(" and ")
      else
        ArgumentError("Only hash && string allowed")
      end
    end

    def method_missing(method, *args, &block)
      @self_before_instance_eval.send(method, *args, &block)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
picturefill-0.1.0 lib/picturefill/context.rb