-
-
Notifications
You must be signed in to change notification settings - Fork 540
/
application_name.rb
99 lines (85 loc) · 2.3 KB
/
application_name.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
98
99
module Lotus
# An application name.
#
# @since x.x.x
class ApplicationName
# A list of words that are prohibited from forming the application name
#
# @since x.x.x
RESERVED_WORDS = %w(lotus).freeze
# Initialize and check against reserved words
#
# An application name needs to be translated in quite a few ways:
# First, it must be checked against a list of reserved words and rejected
# if it is invalid. Secondly, assuming it is not invalid, it must be able
# to be output roughly as given, but with the following changes:
#
# 1. downcased,
# 2. with surrounding spaces removed,
# 3. with internal whitespace rendered as underscores
# 4. with underscores de-duplicated
#
# which is the default output. It must also be transformable into an
# environment variable.
#
# @return [Lotus::ApplicationName] a new instance of the application name
#
# @since x.x.x
def initialize(name)
@name = sanitize(name)
ensure_validity!
end
# Returns the cleaned application name.
#
# @example
# ApplicationName.new("my-App ").to_s # => "my-app"
#
# @since x.x.x
def to_s
@name
end
# Returns the application name uppercased with non-alphanumeric characters
# as underscores.
#
# @example
# ApplicationName.new("my-app").to_env_s => "MY_APP"
#
# @since x.x.x
def to_env_s
@name.upcase.gsub(/\W/, '_')
end
# Returns true if a potential application name matches one of the reserved
# words.
#
# @example
# Lotus::ApplicationName.invalid?("lotus") # => true
#
# @since x.x.x
def self.invalid?(name)
RESERVED_WORDS.include?(name)
end
private
# Raises RuntimeError with explanation if the provided name is invalid.
#
# @api private
# @since x.x.x
def ensure_validity!
if self.class.invalid?(@name)
raise RuntimeError,
"application name must not be any one of the following: " +
RESERVED_WORDS.join(", ")
end
end
# Cleans a string to be a functioning application name.
#
# @api private
# @since x.x.x
def sanitize(name)
name
.downcase
.strip
.gsub(/\s/, '_')
.gsub(/_{2,}/, '_')
end
end
end