Module: Rack::Freeze

Defined in:
lib/rack/freeze.rb,
lib/rack/freeze/version.rb

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.[](klass) ⇒ Object

Generate a subclass with a generic #freeze method to freeze all instance variables.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rack/freeze.rb', line 35

def self.[] klass
  # Check if the class already has a custom implementation of #freeze.. which we assume works correctly.
  return klass if implements_freeze?(klass)
  
  subclass = Class.new(klass) do
    def freeze
      # This ensures that all class variables are frozen.
      self.instance_variables.each do |name|
        self.instance_variable_get(name).freeze
      end
      
      super
    end
  end
  
  return subclass
end

.implements_freeze?(klass) ⇒ Boolean

Check if the given klass overrides ‘Kernel#freeze`.

Returns:

  • (Boolean)


30
31
32
# File 'lib/rack/freeze.rb', line 30

def self.implements_freeze?(klass)
  klass.instance_method(:freeze).owner != Kernel
end