Rework how strategy constants are identified

Up to this point, we've had to rely on making `Strategy` constants
private to ensure that the only available constants are strategies.
With the current setup, the existence of a constant that's not a
strategy would break `Strategy#strategies` and
`Livecheck#livecheck_strategy_names`.

Instead, we can achieve the same goal by skipping over constants
that aren't a class. Other than saving us from having to make these
constants private, this is necessary to be able to create a
`Strategy` constant that can be used in all strategies.
This commit is contained in:
Sam Ford 2021-08-09 18:18:12 -04:00
parent cd900ef71e
commit cf79ced740
No known key found for this signature in database
GPG Key ID: 95209E46C7FFDEFE
2 changed files with 11 additions and 14 deletions

View File

@ -56,9 +56,11 @@ module Homebrew
# Cache demodulized strategy names, to avoid repeating this work
@livecheck_strategy_names = {}
Strategy.constants.sort.each do |strategy_symbol|
strategy = Strategy.const_get(strategy_symbol)
@livecheck_strategy_names[strategy] = strategy.name.demodulize
Strategy.constants.sort.each do |const_symbol|
constant = Strategy.const_get(const_symbol)
next unless constant.is_a?(Class)
@livecheck_strategy_names[constant] = T.must(constant.name).demodulize
end
@livecheck_strategy_names.freeze
end

View File

@ -75,13 +75,6 @@ module Homebrew
# In rare cases, this can also be a double newline (`\n\n`).
HTTP_HEAD_BODY_SEPARATOR = "\r\n\r\n"
# The `#strategies` method expects `Strategy` constants to be strategies,
# so constants we create need to be private for this to work properly.
private_constant :DEFAULT_PRIORITY, :CURL_CONNECT_TIMEOUT, :CURL_MAX_TIME,
:CURL_PROCESS_TIMEOUT, :DEFAULT_CURL_ARGS,
:PAGE_HEADERS_CURL_ARGS, :PAGE_CONTENT_CURL_ARGS,
:DEFAULT_CURL_OPTIONS, :HTTP_HEAD_BODY_SEPARATOR
# Creates and/or returns a `@strategies` `Hash`, which maps a snake
# case strategy name symbol (e.g. `:page_match`) to the associated
# {Strategy}.
@ -93,10 +86,12 @@ module Homebrew
return @strategies if defined? @strategies
@strategies = {}
constants.sort.each do |strategy_symbol|
key = strategy_symbol.to_s.underscore.to_sym
strategy = const_get(strategy_symbol)
@strategies[key] = strategy
Strategy.constants.sort.each do |const_symbol|
constant = Strategy.const_get(const_symbol)
next unless constant.is_a?(Class)
key = const_symbol.to_s.underscore.to_sym
@strategies[key] = constant
end
@strategies
end