Class: AvatarGenerator::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/avatar_generator/generator.rb

Constant Summary collapse

GRID_SIZE =
5

Instance Method Summary collapse

Constructor Details

#initialize(identifier, size: nil, background: nil) ⇒ Generator

Returns a new instance of Generator.

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
# File 'lib/avatar_generator/generator.rb', line 6

def initialize(identifier, size: nil, background: nil)
  @identifier = identifier
  @image_size = size || AvatarGenerator.configuration.size
  @background = background || AvatarGenerator.configuration.background

  raise ArgumentError, "image size must be at least 5" if @image_size < 5
end

Instance Method Details

#callObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
# File 'lib/avatar_generator/generator.rb', line 14

def call
  bytes = Digest::MD5.digest(@identifier).bytes

  color =
    bytes.first(3)

  grid =
    bytes
    .each_slice(3)
    .select { |row| row.length == 3 }
    .map { |row| mirror_row(row) }
    .flatten
    .each_with_index
    .select { |code, _| code.even? }

  pixel_map =
    grid.map do |_, index|
      cell =
        @image_size / GRID_SIZE

      x =
        (index % GRID_SIZE) * cell

      y =
        (index / GRID_SIZE) * cell

      [
        [x, y],
        [x + cell - 1, y + cell - 1]
      ]
    end

  Image.new(
    color: color,
    image_size: @image_size,
    pixel_map: pixel_map,
    background: @background
  )
end