GitLab utilities
We developed a number of utilities to ease development.
MergeHash
Deep merges an array of hashes:
Gitlab::Utils::MergeHash.merge([{hello:["world"]},{hello:"Everyone"},{hello:{greetings:['Bonjour','Hello','Hallo','Dzien dobry']}},“再见”,"Hallo"])
Gives:
[{hello:["world","Everyone",{greetings:['Bonjour','Hello','Hallo','Dzien dobry']}]},“再见”]
Extracts all keys and values from a hash into an array:
Gitlab::Utils::MergeHash.crush({hello:"world",this:{crushes:["an entire","hash"]}})
Gives:
[:hello,"world",:this,:crushes,"an entire","hash"]
Override
This utility could help us check if a particular method would override another method or not. It has the same idea of Java's
@Override
annotation or Scala'soverride
keyword. However we only do this check whenENV['STATIC_VERIFICATION']
is set to avoid production runtime overhead. This is useful to check:- If we have typos in overriding methods.
- If we renamed the overridden methods, making original overriding methods overrides nothing.
Here's a simple example:
classBasedefexecuteendendclass派生的<Baseextend::Gitlab::Utils::Overrideoverride:execute# /ride check happens heredefexecuteendend
This also works on modules:
moduleExtensionextend::Gitlab::Utils::Overrideoverride:execute# Modules do not check this immediatelydefexecuteendendclass派生的<BaseprependExtension# /ride check happens here, not in the moduleend
StrongMemoize
Memoize the value even if it is
零
orfalse
.We often do
@value ||= compute
, however this doesn't work well ifcompute
might eventually give零
and we don't want to compute again. Instead we could usedefined?
to check if the value is set or not. However it's tedious to write such pattern, andStrongMemoize
would help us use such pattern.Instead of writing patterns like this:
classFinddefresultreturn@resultifdefined?(@result)@result=searchendend
We could write it like:
classFindincludeGitlab::Utils::StrongMemoizedefresultstrong_memoize(:result)dosearchendendend
清晰的记忆
classFindincludeGitlab::Utils::StrongMemoizeendFind.new.clear_memoization(:result)