Class: Const

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

Constant Summary collapse

@@config_path =
Object.const_defined?(:Rails) ? "#{Rails.root}/config/constants.yml" : nil
@@environment =
Object.const_defined?(:Rails) ? Rails.env : 'test'
@@raise_error_on_missing =

if true this will raise an error if method you seek isn’t in constants_hash

false

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(constants_hash) ⇒ Const

Returns a new instance of Const.



58
59
60
# File 'lib/const.rb', line 58

def initialize(constants_hash)
  @constants_hash = constants_hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



25
26
27
28
# File 'lib/const.rb', line 25

def method_missing(method, *args)
  fail_if_constant_missing(method.to_s)
  constants_hash[method.to_s].nil? ? "" : constants_hash[method.to_s].freeze
end

Instance Attribute Details

#constants_hashObject (readonly)

Returns the value of attribute constants_hash.



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

def constants_hash
  @constants_hash
end

Class Method Details

.config_path=(path) ⇒ Object



9
10
11
# File 'lib/const.rb', line 9

def self.config_path=(path)
  @@config_path = path
end

.environment=(environment) ⇒ Object



13
14
15
# File 'lib/const.rb', line 13

def self.environment=(environment)
  @@environment = environment
end

.load!Object

Raises:

  • (ArgumentError)


37
38
39
40
41
42
43
# File 'lib/const.rb', line 37

def self.load!
  raise ArgumentError.new("No config file path specified. Use 'Const.config_path = PATH' to set it up") if @@config_path.nil?
  constants_config = YAML::load(pre_process_constants_file)
  fail_if_environment_missing(@@environment, constants_config)
  constants_hash = constants_config[@@environment] || {}
  @@instance = Const.new(constants_hash)
end

.method_missing(method, *args) ⇒ Object



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

def self.method_missing(method, *args)
  @@instance.send(method).is_a?(Hash) ? Const.new(@@instance.constants_hash[method.to_s]) : @@instance.send(method)
end

.pre_process_constants_fileObject



52
53
54
55
# File 'lib/const.rb', line 52

def self.pre_process_constants_file
  template = File.open(@@config_path).read
  ERB.new(template).result
end

.raise_error_on_missing=(true_false) ⇒ Object



17
18
19
# File 'lib/const.rb', line 17

def self.raise_error_on_missing=(true_false)
  @@raise_error_on_missing = true_false
end