Class: JekyllThumbnail

Inherits:
Liquid::Tag
  • Object
show all
Defined in:
lib/jekyll-thumbnail.rb

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, markup, tokens) ⇒ JekyllThumbnail



20
21
22
23
24
25
26
# File 'lib/jekyll-thumbnail.rb', line 20

def initialize(tag_name, markup, tokens)
  if /(?<source>[^\s]+)\s+(?<dimensions>[^\s]+)/i =~ markup
    @source = source
    @dimensions = dimensions
  end
  super
end

Instance Method Details

#look_up(context, name) ⇒ Object

look up liquid variables source: stackoverflow.com/a/8771374/1489823



10
11
12
13
14
15
16
17
18
# File 'lib/jekyll-thumbnail.rb', line 10

def look_up(context, name)
  lookup = context

  name.split(".").each do |value|
    lookup = lookup[value]
  end

  lookup
end

#render(context) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/jekyll-thumbnail.rb', line 28

def render(context)
  if @source

    # parking

    # also put the parameters into the liquid parser again, to allow variable paths

    source = @source
    source = look_up context, source unless File.readable?(source)
    dimensions = @dimensions

    source_path = "#{source}"
    raise "#{source_path} is not readable" unless File.readable?(source_path)
    ext = File.extname(source)
    desc = dimensions.gsub(/[^\da-z]+/i, '')
    dest_dir = "#{File.dirname(source)}/thumbs"
    Dir.mkdir dest_dir unless Dir.exists? dest_dir
    dest = "#{dest_dir}/#{File.basename(source, ext)}_#{desc}#{ext}"
    dest_path = "#{dest}"

    # only thumbnail the image if it doesn't exist tor is less recent than the source file

    # will prevent re-processing thumbnails for a ton of images...

    if !File.exists?(dest_path) || File.mtime(dest_path) <= File.mtime(source_path)
      # puts ENV.inspect


      puts "Thumbnailing #{source} to #{dest} (#{dimensions})"

      image = MiniMagick::Image.open(source_path)
      image.strip
      image.resize dimensions
      image.quality 60

      second_image = MiniMagick::Image.new("img/watermark-#{dimensions}.png")

      result = image.composite(second_image) do |c|
        c.compose "Over"    # OverCompositeOp

        c.geometry "+20+20" # copy second_image onto first_image from (20, 20)

      end

      result.write dest_path
    end

    """<img src='#{dest}' />"""

    # TODO support relative paths

  else
    "Could not create thumbnail for #{source}. Usage: thumbnail /path/to/local/image.png 50x50"
  end
end