Class: Decidim::Env

Inherits:
Object
  • Object
show all
Defined in:
lib/decidim/env.rb

Overview

This class can be used to parse ENV variables to a set of predefined values For instance, “”, nil, “false” or 0 will all translate into false using valid?

Constant Summary collapse

FALSE_VALUES =
%w(0 false no).freeze

Instance Method Summary collapse

Constructor Details

#initialize(name, default = nil) ⇒ Env

Returns a new instance of Env.



9
10
11
12
13
# File 'lib/decidim/env.rb', line 9

def initialize(name, default = nil)
  @name = name
  @value = ENV.fetch(name, nil)
  @default = default
end

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/decidim/env.rb', line 21

def blank?
  value.blank? || FALSE_VALUES.include?(value.to_s.downcase)
end

#default_or_present_if_existsObject



45
46
47
48
49
# File 'lib/decidim/env.rb', line 45

def default_or_present_if_exists
  return @default unless ENV.has_key?(@name)

  @value.present? && FALSE_VALUES.exclude?(@value.to_s.downcase)
end

#present?Boolean

rubocop:disable Rails/Present

Returns:

  • (Boolean)


26
27
28
# File 'lib/decidim/env.rb', line 26

def present?
  !blank?
end

#to_array(separator: ",") ⇒ Object



51
52
53
54
# File 'lib/decidim/env.rb', line 51

def to_array(separator: ",")
  str = blank? ? @default : value
  str.to_s.split(separator).map(&:strip)
end

#to_boolean_stringObject

rubocop:enable Rails/Present



31
32
33
# File 'lib/decidim/env.rb', line 31

def to_boolean_string
  present?.to_s
end

#to_fObject



40
41
42
43
# File 'lib/decidim/env.rb', line 40

def to_f
  str = blank? ? @default : value
  str.to_s.to_f
end

#to_iObject



35
36
37
38
# File 'lib/decidim/env.rb', line 35

def to_i
  str = blank? ? @default : value
  str.to_s.to_i
end

#valueObject



15
16
17
# File 'lib/decidim/env.rb', line 15

def value
  @value.presence || @default
end