discourse/app/models/global_setting.rb

86 lines
1.7 KiB
Ruby
Raw Normal View History

2013-12-19 23:12:23 -05:00
class GlobalSetting
2013-12-20 00:38:51 -05:00
def self.load_defaults
2013-12-20 01:41:12 -05:00
default_provider = FileProvider.from(File.expand_path('../../../config/discourse_defaults.conf', __FILE__))
default_provider.data.each do |name, default|
2013-12-19 23:12:23 -05:00
define_singleton_method(name) do
provider.lookup(name, default)
end
end
end
class BaseProvider
2013-12-20 00:17:21 -05:00
def self.coerce(setting)
return setting == "true" if setting == "true" || setting == "false"
return $1.to_i if setting.to_s.strip =~ /^([0-9]+)$/
setting
end
def resolve(current, default)
BaseProvider.coerce(
if current.present?
current
else
default.present? ? default : nil
end
)
2013-12-19 23:12:23 -05:00
end
end
2013-12-20 00:17:21 -05:00
class FileProvider < BaseProvider
2013-12-20 00:38:51 -05:00
attr_reader :data
2013-12-20 00:17:21 -05:00
def self.from(file)
if File.exists?(file)
parse(file)
end
end
def initialize(file)
@file = file
@data = {}
end
def read
File.read(@file).split("\n").each do |line|
if line =~ /([a-z_]+)\s*=\s*(\"([^\"]*)\"|\'([^\']*)\'|[^#]*)/
@data[$1.strip.to_sym] = ($4 || $3 || $2).strip
end
end
end
def lookup(key,default)
2013-12-20 01:09:51 -05:00
var = @data[key]
resolve(var, var.nil? ? default : "")
2013-12-20 00:17:21 -05:00
end
private
def self.parse(file)
provider = self.new(file)
provider.read
provider
2013-12-19 23:12:23 -05:00
end
end
2013-12-20 00:17:21 -05:00
class EnvProvider < BaseProvider
def lookup(key, default)
2013-12-20 01:07:08 -05:00
var = ENV["DISCOURSE_" << key.to_s.upcase]
resolve(var , var.nil? ? default : nil)
2013-12-20 00:17:21 -05:00
end
2013-12-19 23:12:23 -05:00
end
class << self
attr_accessor :provider
end
2013-12-20 00:38:51 -05:00
load_defaults
2013-12-19 23:12:23 -05:00
@provider =
2013-12-20 00:17:21 -05:00
FileProvider.from(File.expand_path('../../../config/discourse.conf', __FILE__)) ||
2013-12-19 23:12:23 -05:00
EnvProvider.new
end