Panayotis Matsinopoulos

Senior Software Engineer: Love Creating Software, Taking Entrepreneurial Risks, Teaching Computer Programming & Blogging here or in many other places

How to Define and Use Class-level Variables While Mixing in Modules

| Comments

There are sometimes that you might want to use class-level variables in a reusable module. How will you do that? Here is a sample ruby program that does that:

Example of Modules and class-level variables
1
2
3
4
5
6
7
8
9
10
11
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
require 'set'

module Cacheable
  def self.included(base)
    base.send :extend, ClassMethods
  end

  module ClassMethods
    def cached_keys
      @cached_keys ||= Set.new
    end

    def add_cached_key(key_sym)
      @cached_keys ||= Set.new
      @cached_keys.add(key_sym)
    end
  end
end

class A
  include Cacheable
end

class B
  include Cacheable
end

puts "A cached keys: #{A.cached_keys.inspect}"
puts "B cached keys: #{B.cached_keys.inspect}"

A.add_cached_key(:a)
puts "A cached keys: #{A.cached_keys.inspect}"
puts "B cached keys: #{B.cached_keys.inspect}"

B.add_cached_key(:b)
puts "A cached keys: #{A.cached_keys.inspect}"
puts "B cached keys: #{B.cached_keys.inspect}"

A.add_cached_key(:aa)
puts "A cached keys: #{A.cached_keys.inspect}"
puts "B cached keys: #{B.cached_keys.inspect}"

B.add_cached_key(:bb)
puts "A cached keys: #{A.cached_keys.inspect}"
puts "B cached keys: #{B.cached_keys.inspect}"

If you run the above ruby script, you will get the following output:

Output of running the above ruby script
1
2
3
4
5
6
7
8
9
10
A cached keys: #<Set: {}>
B cached keys: #<Set: {}>
A cached keys: #<Set: {:a}>
B cached keys: #<Set: {}>
A cached keys: #<Set: {:a}>
B cached keys: #<Set: {:b}>
A cached keys: #<Set: {:aa, :a}>
B cached keys: #<Set: {:b}>
A cached keys: #<Set: {:aa, :a}>
B cached keys: #<Set: {:bb, :b}>

In the above example, we keep a class level Set of symbols (@cached_keys). We want every class that mixes in Cacheable to have its own instance of that Set.

Comments