We have a gem where we have a method #display_name
, this method returns localized name if I18n gem is defined else falls back to default_display_name.
Following is the current implementation:
def display_name
if Module.const_defined?(:I18n)
localized_display_name
else
default_display_name
end
end
We want to refactor it as on every method call we are calling Module#const_defined?
.
Following is the proposed implementation.
if Module.const_defined?(:I18n)
def display_name
localized_display_name
end
else
def display_name
default_display_name
end
end
On surface level this looks ok but we have a concern that now we are assuming the require order of gem. So, my question is, should the gem assume the other gem is loaded (in this case I18n) or it should lazily checks like current implementation.
And any other suggestions for refactoring/optimizations are welcome. Thanks in advance!
from ruby documentation
require(name) → true or false
Loads the givenname
, returningtrue
if successful andfalse
if the feature is already loaded.
it implies that if you require
is not loading a file\gem more than once. for that reason, i will explicit state the requirement in the entry point of your program.
you can always test if a rubygem is present by using
Gem.loaded_specs.has_key? 'gem-name'