Class: BBortcodes::Context

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/bbortcodes/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(initial_data = {}) ⇒ Context

Returns a new instance of Context.



9
10
11
12
13
# File 'lib/bbortcodes/context.rb', line 9

def initialize(initial_data = {})
  super() # Initialize MonitorMixin
  @data = initial_data.dup
  @counters = Hash.new(0)
end

Instance Method Details

#[](key) ⇒ Object

Allow hash-like access



76
77
78
# File 'lib/bbortcodes/context.rb', line 76

def [](key)
  get(key)
end

#[]=(key, value) ⇒ Object



80
81
82
# File 'lib/bbortcodes/context.rb', line 80

def []=(key, value)
  set(key, value)
end

#counter(counter_name) ⇒ Integer

Get current counter value without incrementing

Parameters:

  • The counter name (normalized to string)

Returns:

  • The current counter value



53
54
55
56
57
# File 'lib/bbortcodes/context.rb', line 53

def counter(counter_name)
  synchronize do
    @counters[counter_name.to_s]
  end
end

#get(key) ⇒ Object

Get a value from the context

Parameters:

  • The key to look up (normalized to string)



17
18
19
20
21
# File 'lib/bbortcodes/context.rb', line 17

def get(key)
  synchronize do
    @data[key.to_s]
  end
end

#increment(counter_name) ⇒ Integer

Increment and return a counter (thread-safe atomic operation) Useful for generating unique IDs like SHORTCODE-1, SHORTCODE-2, etc.

Parameters:

  • The counter name (normalized to string)

Returns:

  • The incremented counter value



44
45
46
47
48
# File 'lib/bbortcodes/context.rb', line 44

def increment(counter_name)
  synchronize do
    @counters[counter_name.to_s] += 1
  end
end

#key?(key) ⇒ Boolean

Check if a key exists

Parameters:

  • The key to check (normalized to string)

Returns:



34
35
36
37
38
# File 'lib/bbortcodes/context.rb', line 34

def key?(key)
  synchronize do
    @data.key?(key.to_s)
  end
end

#reset_counter(counter_name) ⇒ Object

Reset a counter to 0

Parameters:

  • The counter name (normalized to string)



61
62
63
64
65
# File 'lib/bbortcodes/context.rb', line 61

def reset_counter(counter_name)
  synchronize do
    @counters[counter_name.to_s] = 0
  end
end

#set(key, value) ⇒ Object

Set a value in the context

Parameters:

  • The key to set (normalized to string)

  • The value to set



26
27
28
29
30
# File 'lib/bbortcodes/context.rb', line 26

def set(key, value)
  synchronize do
    @data[key.to_s] = value
  end
end

#to_hHash

Access all data (returns a duplicate to prevent external modification)

Returns:

  • A copy of the context data



69
70
71
72
73
# File 'lib/bbortcodes/context.rb', line 69

def to_h
  synchronize do
    @data.dup
  end
end