class Wallaby::ClassHash
This is a constant-safe hash that stores Class key/value as String and returns value as Class if it was a Class.
It can be used for global methods (e.g. {Wallaby::Map.mode_map}) which cache the computed result, so that when Rails reloads, it won't complain that old Class constants still exist in ObjectSpace (see github.com/wallaby-rails/wallaby/issues/181).
“` A copy of SupportAdmin::ApplicationAuthorizer has been removed from the module tree but is still active! “`
As there won't be any Class constants being stored, they will converted to String in {#internal} Hash.
Attributes
@!attribute [r] internal @return [Hash] The hash to store Class keys/values as String.
Public Class Methods
@param [Hash] hash
# File lib/wallaby/class_hash.rb, line 22 def initialize(hash = {}) @internal = (hash || {}) .transform_keys(&method(:to_class_name)) .transform_values(&method(:to_class_name)) end
Public Instance Methods
Return the value for the given key, and convert the value back to Class if it was a Class
# File lib/wallaby/class_hash.rb, line 57 def [](key) to_class @internal[to_class_name(key)] end
Save the key/value to the {#internal} hash, and convert the Class key/value to String
# File lib/wallaby/class_hash.rb, line 52 def []=(key, value) @internal[to_class_name(key)] = to_class_name(value) end
Ensure to freeze the {#internal} @return [Wallaby::ClassHash] self
# File lib/wallaby/class_hash.rb, line 74 def freeze @internal.freeze super end
@param other [Hash] @return [Wallaby::ClassHash] new Class hash
# File lib/wallaby/class_hash.rb, line 63 def merge(other) self.class.new origin.merge(other.try(:origin) || other) end
@!attribute [r] origin @return [Hash] The original hash.
# File lib/wallaby/class_hash.rb, line 31 def origin # NOTE: DO NOT cache it by using instance variable! @internal .transform_keys(&method(:to_class)) .transform_values(&method(:to_class)) .reject { |k, v| k.nil? || v.nil? } end
@return [Wallaby::ClassHash] new Class hash
# File lib/wallaby/class_hash.rb, line 68 def select(&block) self.class.new origin.select(&block) end
Protected Instance Methods
Convert to Class
# File lib/wallaby/class_hash.rb, line 87 def to_class(pair) val, is_class = pair is_class ? val.constantize : val rescue NameError Logger.error "`#{val}` is not a valid Class name." end
Convert to Class name
# File lib/wallaby/class_hash.rb, line 82 def to_class_name(klass) klass.is_a?(Class) ? [klass.name, true] : [klass, false] end