Class: LetterAvatar::Avatar

Inherits:
Object
  • Object
show all
Defined in:
lib/letter_avatar/avatar.rb

Defined Under Namespace

Classes: Identity

Constant Summary collapse

VERSION =

BUMP UP if avatar algorithm changes

2
FULLSIZE =

Largest avatar generated, one day when pixel ratio hit 3 we will need to change this

600
FILL_COLOR =
'rgba(255, 255, 255, 0.65)'.freeze
FONT_FILENAME =
File.join(File.expand_path('../../', File.dirname(__FILE__)), 'Roboto-Medium')

Class Method Summary collapse

Class Method Details

.cache_pathObject



28
29
30
# File 'lib/letter_avatar/avatar.rb', line 28

def cache_path
  "#{LetterAvatar.cache_base_path || 'public/system'}/letter_avatars/#{VERSION}"
end

.cached_path(identity, size) ⇒ Object



50
51
52
53
54
55
# File 'lib/letter_avatar/avatar.rb', line 50

def cached_path(identity, size)
  dir = "#{cache_path}/#{identity.letter}/#{identity.color.join('_')}"
  FileUtils.mkdir_p(dir)

  "#{dir}/#{size}.png"
end

.darken(color, pct) ⇒ Object



82
83
84
85
86
# File 'lib/letter_avatar/avatar.rb', line 82

def darken(color, pct)
  color.map do |n|
    (n.to_f * pct).to_i
  end
end

.fullsize_path(identity) ⇒ Object



57
58
59
# File 'lib/letter_avatar/avatar.rb', line 57

def fullsize_path(identity)
  cached_path(identity, FULLSIZE)
end

.generate(username, size, opts = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/letter_avatar/avatar.rb', line 32

def generate(username, size, opts = nil)
  identity = Identity.from_username(username)

  cache = true
  cache = false if opts && opts[:cache] == false

  size = FULLSIZE if size > FULLSIZE
  filename = cached_path(identity, size)

  return filename if cache && File.exist?(filename)

  fullsize = fullsize_path(identity)
  generate_fullsize(identity) if !cache || !File.exist?(fullsize)

  LetterAvatar.resize(fullsize, filename, size, size) if size != FULLSIZE
  filename
end

.generate_fullsize(identity) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/letter_avatar/avatar.rb', line 61

def generate_fullsize(identity)
  filename = fullsize_path(identity)

  LetterAvatar.execute(
    %W(
      convert
      -size #{FULLSIZE}x#{FULLSIZE}
      xc:#{to_rgb(identity.color)}
      -pointsize #{LetterAvatar.pointsize}
      -font #{LetterAvatar.font}
      -weight #{LetterAvatar.weight}
      -fill '#{LetterAvatar.fill_color}'
      -gravity Center
      -annotate #{LetterAvatar.annotate_position} '#{identity.letter}'
      '#{filename}'
    ).join(' ')
  )

  filename
end

.to_rgb(color) ⇒ Object



88
89
90
91
# File 'lib/letter_avatar/avatar.rb', line 88

def to_rgb(color)
  r, g, b = color
  "'rgb(#{r},#{g},#{b})'"
end