Class: CMDx::Context

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/cmdx/context.rb

Overview

A hash-like context object that provides a flexible way to store and access key-value pairs during task execution. Keys are automatically converted to symbols for consistency.

The Context class extends Forwardable to delegate common hash methods and provides additional convenience methods for working with context data.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Context

Creates a new Context instance from the given arguments.

Examples:

context = Context.new(name: "John", age: 30)
context[:name] # => "John"

Parameters:

  • args (Hash, Object) (defaults to: {})

    arguments to initialize the context with

Options Hash (args):

  • :key (Object)

    the key-value pairs to store in the context

Raises:

  • (ArgumentError)

    when args doesn’t respond to ‘to_h` or `to_hash`



41
42
43
44
45
46
47
48
49
50
# File 'lib/cmdx/context.rb', line 41

def initialize(args = {})
  @table =
    if args.respond_to?(:to_hash)
      args.to_hash
    elsif args.respond_to?(:to_h)
      args.to_h
    else
      raise ArgumentError, "must respond to `to_h` or `to_hash`"
    end.transform_keys(&:to_sym)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, **_kwargs) {|Object| ... } ⇒ Object (private)

Handles method calls that don’t match defined methods. Supports assignment-style calls (e.g., ‘name=`) and key access.

Parameters:

  • method_name (Symbol)

    the method name that was called

  • args (Array<Object>)

    arguments passed to the method

  • _kwargs (Hash)

    keyword arguments (unused)

Options Hash (**_kwargs):

  • :* (Object)

    Any keyword arguments (unused)

Yields:

  • (Object)

    optional block

Returns:

  • (Object)

    the result of the method call



264
265
266
267
268
# File 'lib/cmdx/context.rb', line 264

def method_missing(method_name, *args, **_kwargs, &)
  fetch(method_name) do
    store(method_name[0..-2], args.first) if method_name.end_with?("=")
  end
end

Instance Attribute Details

#tableHash{Symbol => Object} (readonly) Also known as: to_h

Returns the internal hash storing context data.

Examples:

context.table # => { name: "John", age: 30 }

Returns:

  • (Hash{Symbol => Object})

    The internal hash table



22
23
24
# File 'lib/cmdx/context.rb', line 22

def table
  @table
end

Class Method Details

.build(context = {}) ⇒ Context

Builds a Context instance, reusing existing unfrozen contexts when possible.

Examples:

existing = Context.new(name: "John")
built = Context.build(existing) # reuses existing context
built.object_id == existing.object_id # => true

Parameters:

  • context (Context, Object) (defaults to: {})

    the context to build from

Options Hash (context):

  • :key (Object)

    the key-value pairs to store in the context

Returns:

  • (Context)

    a Context instance, either new or reused



65
66
67
68
69
70
71
72
73
# File 'lib/cmdx/context.rb', line 65

def self.build(context = {})
  if context.is_a?(self) && !context.frozen?
    context
  elsif context.respond_to?(:context)
    build(context.context)
  else
    new(context)
  end
end

Instance Method Details

#[](key) ⇒ Object?

Retrieves a value from the context by key.

Examples:

context = Context.new(name: "John")
context[:name] # => "John"
context["name"] # => "John" (automatically converted to symbol)

Parameters:

  • key (String, Symbol)

    the key to retrieve

Returns:

  • (Object, nil)

    the value associated with the key, or nil if not found



87
88
89
# File 'lib/cmdx/context.rb', line 87

def [](key)
  table[key.to_sym]
end

#delete!(key) {|key| ... } ⇒ Object?

Deletes a key-value pair from the context.

Examples:

context = Context.new(name: "John", age: 30)
context.delete!(:age) # => 30
context.delete!(:city) { |key| "Key #{key} not found" } # => "Key city not found"

Parameters:

  • key (String, Symbol)

    the key to delete

Yields:

  • (key)

    a block to handle the case when key is not found

Returns:

  • (Object, nil)

    the deleted value, or the block result if key not found



182
183
184
# File 'lib/cmdx/context.rb', line 182

def delete!(key, &)
  table.delete(key.to_sym, &)
end

#dig(key, *keys) ⇒ Object?

Digs into nested structures using the given keys.

Examples:

context = Context.new(user: {profile: {name: "John"}})
context.dig(:user, :profile, :name) # => "John"
context.dig(:user, :profile, :age) # => nil

Parameters:

  • key (String, Symbol)

    the first key to dig with

  • keys (Array<String, Symbol>)

    additional keys for deeper digging

Returns:

  • (Object, nil)

    the value found by digging, or nil if not found



232
233
234
# File 'lib/cmdx/context.rb', line 232

def dig(key, *keys)
  table.dig(key.to_sym, *keys)
end

#eql?(other) ⇒ Boolean Also known as: ==

Compares this context with another object for equality.

Examples:

context1 = Context.new(name: "John")
context2 = Context.new(name: "John")
context1 == context2 # => true

Parameters:

  • other (Object)

    the object to compare with

Returns:

  • (Boolean)

    true if other is a Context with the same data



198
199
200
# File 'lib/cmdx/context.rb', line 198

def eql?(other)
  other.is_a?(self.class) && (to_h == other.to_h)
end

#fetch(key) {|key| ... } ⇒ Object

Fetches a value from the context by key, with optional default value.

Examples:

context = Context.new(name: "John")
context.fetch(:name) # => "John"
context.fetch(:age, 25) # => 25
context.fetch(:city) { |key| "Unknown #{key}" } # => "Unknown city"

Parameters:

  • key (String, Symbol)

    the key to fetch

Yields:

  • (key)

    a block to compute the default value

Returns:

  • (Object)

    the value associated with the key, or the default/default block result



124
125
126
# File 'lib/cmdx/context.rb', line 124

def fetch(key, ...)
  table.fetch(key.to_sym, ...)
end

#fetch_or_store(key, value = nil) {|key| ... } ⇒ Object

Fetches a value from the context by key, or stores and returns a default value if not found.

Examples:

context = Context.new(name: "John")
context.fetch_or_store(:name, "Default") # => "John" (existing value)
context.fetch_or_store(:age, 25) # => 25 (stored and returned)
context.fetch_or_store(:city) { |key| "Unknown #{key}" } # => "Unknown city" (stored and returned)

Parameters:

  • key (String, Symbol)

    the key to fetch or store

  • value (Object) (defaults to: nil)

    the default value to store if key is not found

Yields:

  • (key)

    a block to compute the default value to store

Returns:

  • (Object)

    the existing value if key is found, otherwise the stored default value



144
145
146
147
148
# File 'lib/cmdx/context.rb', line 144

def fetch_or_store(key, value = nil)
  table.fetch(key.to_sym) do
    table[key.to_sym] = block_given? ? yield : value
  end
end

#key?(key) ⇒ Boolean

Checks if the context contains a specific key.

Examples:

context = Context.new(name: "John")
context.key?(:name) # => true
context.key?(:age) # => false

Parameters:

  • key (String, Symbol)

    the key to check

Returns:

  • (Boolean)

    true if the key exists in the context



215
216
217
# File 'lib/cmdx/context.rb', line 215

def key?(key)
  table.key?(key.to_sym)
end

#merge!(args = {}) ⇒ Context

Merges the given arguments into the current context, modifying it in place.

Examples:

context = Context.new(name: "John")
context.merge!(age: 30, city: "NYC")
context.to_h # => {name: "John", age: 30, city: "NYC"}

Parameters:

  • args (Hash, Object) (defaults to: {})

    arguments to merge into the context

Options Hash (args):

  • :key (Object)

    the key-value pairs to merge

Returns:

  • (Context)

    self for method chaining



163
164
165
166
# File 'lib/cmdx/context.rb', line 163

def merge!(args = {})
  args.to_h.each { |key, value| self[key.to_sym] = value }
  self
end

#store(key, value) ⇒ Object Also known as: []=

Stores a key-value pair in the context.

Examples:

context = Context.new
context.store(:name, "John")
context[:name] # => "John"

Parameters:

  • key (String, Symbol)

    the key to store

  • value (Object)

    the value to store

Returns:

  • (Object)

    the stored value



104
105
106
# File 'lib/cmdx/context.rb', line 104

def store(key, value)
  table[key.to_sym] = value
end

#to_sString

Converts the context to a string representation.

Examples:

context = Context.new(name: "John", age: 30)
context.to_s # => "name: John, age: 30"

Returns:

  • (String)

    a formatted string representation of the context data



245
246
247
# File 'lib/cmdx/context.rb', line 245

def to_s
  Utils::Format.to_str(to_h)
end