Module: FantasyIdentifiable

Extended by:
ActiveSupport::Concern
Defined in:
lib/fantasy_identifiable.rb,
lib/fantasy_identifiable/version.rb

Constant Summary collapse

VERSION =
"0.1.2"

Instance Method Summary collapse

Instance Method Details

#friendly_token(length = 20) ⇒ Object



66
67
68
69
70
71
# File 'lib/fantasy_identifiable.rb', line 66

def friendly_token(length = 20)
  # To calculate real characters, we must perform this operation.
  # See SecureRandom.urlsafe_base64
  rlength = (length * 3) / 4
  SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
end

#generate_identifiersObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/fantasy_identifiable.rb', line 15

def generate_identifiers
  self.class.identifier_fields.each do |field_name, field_type|
    next if self.identifier.present?

    case field_type
    when :friendly
      set_friendly_identifier field_name
    when :fantasy
      set_fantasy_identifier field_name
    else
      set_uuid_identifier field_name
    end
  end
end

#identifier_with(field_name, &block) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/fantasy_identifiable.rb', line 38

def identifier_with(field_name, &block)
  loop do
    new_id = block.call
    if self.class.where("#{field_name} LIKE ?", new_id).empty?
      send("#{field_name}=", new_id)
      break
    end
  end
end

#random_fantasy_identifierObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/fantasy_identifiable.rb', line 73

def random_fantasy_identifier
  (
    (
      Faker::Hipster.words(number: 4) +
      [
        Faker::TvShows::Stargate.planet,
        Faker::TvShows::GameOfThrones.city,
        Faker::TvShows::GameOfThrones.dragon,
        Faker::Movies::HitchhikersGuideToTheGalaxy.planet,
        Faker::Creature::Animal.name,
        Faker::Creature::Cat.name,
        Faker::Creature::Dog.name,
        Faker::Fantasy::Tolkien.race,
        Faker::Books::Dune.city,
        Faker::Books::Dune.planet,
        Faker::Verb.past,
        Faker::Science.element,
        Faker::Name.first_name,
        Faker::Job.key_skill,
        Faker::Hacker.noun
      ]
    ).sample(3) +
    [friendly_token(3).downcase.tr("-_", "ab")]
  ).join("-").delete(" ").downcase.gsub(/[^\-0-9A-Za-z]/, '')
end

#set_fantasy_identifier(field_name) ⇒ Object



48
49
50
51
52
# File 'lib/fantasy_identifiable.rb', line 48

def set_fantasy_identifier field_name
  identifier_with(field_name) do
    random_fantasy_identifier
  end
end

#set_friendly_identifier(field_name) ⇒ Object



54
55
56
57
58
# File 'lib/fantasy_identifiable.rb', line 54

def set_friendly_identifier field_name
  identifier_with(field_name) do
    friendly_token(20).downcase.tr("-_", "ab")
  end
end

#set_uuid_identifier(field_name) ⇒ Object



60
61
62
63
64
# File 'lib/fantasy_identifiable.rb', line 60

def set_uuid_identifier field_name
  identifier_with(field_name) do
    SecureRandom.uuid
  end
end