Class: Msgtrail::Slug

Inherits:
Object
  • Object
show all
Defined in:
lib/msgtrail/slug.rb

Class Method Summary collapse

Class Method Details

.bucketnameify(string) ⇒ Object

Create S3-safe slug.

S3 bucket names must comply to these naming rules:

  • must be between 3 and 63 characters long

  • must be lowercase a-z

  • may use numbers 0-9

  • may use periods & dashes (and thus not _ or / or )

  • must start with letter or number

  • may not end with dash

  • may not have consecutive periods

  • may not use dashes adjacent to periods (i.e. no .- or -.)

  • may not not be formatted as a IP address

Reference: tinyurl.com/yycoeogm

Note: although periods are allowed this methods rejects them for sake of simplicity



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/msgtrail/slug.rb', line 36

def self.bucketnameify(string)
  #
  # Steps:
  # - change to lowercase
  # - remove periods
  # - truncate to 63 characters
  # - replace invalid characters
  # - condense multiple dashes into one dash
  # - replace leading dashes
  # - replace trailing dashes
  # - pad string with zeros if shorter than 3 characters
  #
  string.downcase
        .gsub(/\.*/, '')
        .slice(0..62)
        .gsub(/[^a-z,0-9,-]/, '-')
        .gsub(/-+/, '-')
        .gsub(/\A-*/, '')
        .gsub(/-*\Z/, '')
        .ljust(3, '0')
end

.generate(title, date, time) ⇒ Object



4
5
6
7
8
9
# File 'lib/msgtrail/slug.rb', line 4

def self.generate(title, date, time)
  ymd = date.split(/\D/).map(&:to_i)
  hm = time.split(/\D/).map(&:to_i)
  datestamp = sprintf("%04d%02d%02d-%02d%02d", ymd[0], ymd[1], ymd[2], hm[0], hm[1])
  bucketnameify("#{datestamp}-#{slugify(title)}")
end

.slugify(title) ⇒ Object

Create URL-safe slug



12
13
14
15
16
17
# File 'lib/msgtrail/slug.rb', line 12

def self.slugify(title)
  URI.encode_www_form_component(title)
     .gsub(/%[0-9A-F]{2}/, '-')
     .gsub(/-+/, '-')
     .downcase
end