Module:BDD/localize

From Omniversalis
Revision as of 06:39, 27 May 2017 by Vivaporius (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:BDD/localize/doc

-- submodule for Behavior Driven Development testing framework
-- © John Erling Blad, Creative Commons by Attribution 3.0

local localize = {}

-- @var contLang the language used for localization
-- @todo should adapt to the user language when called through the api
localize.contLang = mw.language.getContentLanguage()

-- @var languages the chain of fallback languages to use given the content language
localize.languages = localize.contLang:getFallbackLanguages() or {}
-- the fallback languages must be prepended with the content language
table.insert( localize.languages, 1, localize.contLang:getCode() )

-- @var fallbacks the message sets in the sequence given by the language sequence
localize.fallbacks = {}
-- load each of the message sets in sequence
for i,v in ipairs(localize.languages) do
	mw.log(v)
	localize.fallbacks[i] = mw.loadData('Module:BDD/localize/'..v) or {}
end

-- metatable for the export
local mt = {
	__call = function ( self, key, ...)
		local msg = mw.message.new( 'bdd-' .. key, ... )
		-- if blank, then try to find in our localization files
		if not msg or msg:isBlank() then
			local keep = msg
			for i,v in ipairs(localize.languages) do
				local str = localize.fallbacks[i][key]
				if str then
					msg = mw.message.newRawMessage( str, ... )
					if msg and msg:exists() then
						return msg
					end
				end
			end
			msg = keep
		end
		assert(msg, "invalid message: " .. key .. " is not a defined string" )
		-- this will also return blank messages!
		return msg
	end
}

-- install the metatable
setmetatable(localize, mt)

return localize