Module: Immutable::ClassMethods

Defined in:
lib/immutable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allow_method_overrideObject

module_eval



59
60
61
62
63
64
# File 'lib/immutable.rb', line 59

def self.allow_method_override
  instance_variable_set("@#{UNIQ}_in_method_added", true)
  yield
ensure
  instance_variable_set("@#{UNIQ}_in_method_added", false)
end

.in_method_added?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/immutable.rb', line 66

def self.in_method_added?
  instance_variable_get("@#{UNIQ}_in_method_added")
end

Instance Method Details

#immutable_method(*args) ⇒ Object Also known as: immutable_methods



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/immutable.rb', line 12

def immutable_method(*args)
  # Initialize variables
  @immutable_methods = [] if @immutable_methods.nil?
  @silent_immutable_methods = [] if @silent_immutable_methods.nil?
  instance_variable_set("@#{UNIQ}_in_method_added", false)

  opts = args.last.is_a?(Hash) ? args.pop : {}
  
  args.each do |method|
    alias_method "#{UNIQ}_old_#{method}", method
  end
  
  # Build list of immutable methods
  @immutable_methods += args
  @silent_immutable_methods += args if opts[:silent]

  @opts = opts
  module_eval do
    def self.method_added(sym)
      if @immutable_methods
        @immutable_methods.each do |method|
          if method && sym == method.to_sym && !in_method_added?
            unless @silent_immutable_methods.include?(method)
              raise CannotOverrideMethod, "Cannot override the immutable method: #{sym}"
            end
            
            allow_method_override do
              self.module_eval <<-"end;"
                def #{method}(*args, &block)
                  #{UNIQ}_old_#{method}(*args, &block)
                end
              end;
            end
          end 
        end # @args.each
      end # @immutable_methods
    end # def self.method_added()

    def self.method_undefined(sym)
      method_added(sym)
    end

    def self.method_removed(sym)
      method_added(sym)
    end
  end # module_eval

  def self.allow_method_override
    instance_variable_set("@#{UNIQ}_in_method_added", true)
    yield
  ensure
    instance_variable_set("@#{UNIQ}_in_method_added", false)
  end

  def self.in_method_added?
    instance_variable_get("@#{UNIQ}_in_method_added")
  end
end