Class: LeMeme::MemeLib

Inherits:
Object
  • Object
show all
Defined in:
lib/le_meme/meme_lib.rb

Overview

Utility for easily generating memes based off templates

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*dirs) ⇒ MemeLib

Creates a meme library

Parameters:

  • *dirs (String)

    Directory glob patterns to meme templates


9
10
11
12
# File 'lib/le_meme/meme_lib.rb', line 9

def initialize(*dirs)
  @memes = {}
  dirs.each(&method(:load_directory!))
end

Instance Attribute Details

#memesObject (readonly)

Returns the value of attribute memes


4
5
6
# File 'lib/le_meme/meme_lib.rb', line 4

def memes
  @memes
end

Class Method Details

.new_with_default_memesMemeLib

Creates a meme library, preloaded with the included templates

Returns:


17
18
19
20
# File 'lib/le_meme/meme_lib.rb', line 17

def self.new_with_default_memes
  path = File.join(File.dirname(File.expand_path(__FILE__)), '..', '..', 'memes', '*')
  new(path)
end

Instance Method Details

#load_directory!(dir) ⇒ Hash

Loads a directory into the MemeLib, for template consumption Clobbers any existing templates

Parameters:

  • dir (String)

    Directory glob pattern to meme templates

Returns:

  • (Hash)

    Hash of all templates and their filepaths


27
28
29
30
31
32
33
34
# File 'lib/le_meme/meme_lib.rb', line 27

def load_directory!(dir)
  paths = Dir.glob(dir).grep LeMeme::IMAGE_EXTENSIONS
  @memes.merge!(paths.reduce({}) do |images, path|
    path = File.expand_path(path)
    name = path.split.last.sub(LeMeme::IMAGE_EXTENSIONS, '').to_s
    images.merge(name => path)
  end)
end

#meme(template: nil, top: nil, bottom: nil, watermark: nil) ⇒ LeMeme::Meme

Create a meme from a template

Parameters:

  • template: (String) (defaults to: nil)

    nil The template to use. Omit for random template

  • top: (String) (defaults to: nil)

    nil

  • bottom: (String) (defaults to: nil)

    nil

  • watermark: (String) (defaults to: nil)

    nil

Returns:


43
44
45
46
47
# File 'lib/le_meme/meme_lib.rb', line 43

def meme(template: nil, top: nil, bottom: nil, watermark: nil)
  path = template.nil? ? @memes.values.sample : @memes[template]

  Meme.new(path, top: top, bottom: bottom, watermark: watermark)
end