Class: SafeOstruct

Inherits:
Object
  • Object
show all
Defined in:
lib/safe_ostruct.rb,
lib/safe_ostruct/version.rb

Overview

SafeOstruct

SafeOstruct is a flexible struct-like class that allows dynamic initialization of attributes using keyword arguments. It handles missing methods gracefully by returning nil instead of raising a NoMethodError for undefined attributes or methods. This class use Symbolic-Hash and its underlying data structure.

Additionally, it supports dynamically adding and removing attributes. The object allows access to its attributes using both methods and hash-style key access with symbols or strings.

Key features:

  • Define attributes dynamically with keyword arguments.
  • Handle missing methods by returning nil instead of raising NoMethodError.
  • Support both symbol and string access for attributes.
  • Dynamically add or update attributes using method assignment or hash-style assignment.
  • Remove attributes dynamically using delete_field.

Example usage:

obj = SafeOstruct.new(name: 'John Doe')

# Accessing defined attributes
obj.name           # => 'John Doe'
obj[:name]         # => 'John Doe'
obj['name']        # => 'John Doe'

# Adding new attributes dynamically
obj.address = '123 Main St'
obj.address        # => '123 Main St'
obj[:address]      # => '123 Main St'
obj['address']     # => '123 Main St'

# Accessing an undefined attribute returns nil
obj.age            # => nil
obj[:age]          # => nil
obj['age']         # => nil

# Deleting an attribute
obj.delete_field(:address)
obj.address        # => nil
obj.respond_to?(:address) # => false

# Converting to a hash
hash_representation = obj.to_h
# hash_representation => { name: 'John Doe' }

This class simplifies working with dynamic or optional attributes and allows for greater flexibility in handling data structures, especially when attribute names may not be known in advance or when optional fields are common.

Constant Summary collapse

VERSION =
"1.0.0".freeze

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ SafeOstruct

Initializes the SafeOstruct with attributes provided as keyword arguments or a hash.

Parameters:

  • kwargs (Hash)

    the attributes to initialize the struct with



56
57
58
# File 'lib/safe_ostruct.rb', line 56

def initialize(**kwargs)
  @attributes = kwargs.transform_keys(&:to_sym)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &_block) ⇒ Object?

Handles missing methods dynamically, including attribute assignment

Parameters:

  • method_name (Symbol)

    the name of the missing method

  • args (Array)

    the arguments passed to the missing method

  • block (Proc)

    an optional block passed to the missing method

Returns:

  • (Object, nil)

    the value of the attribute, or nil if undefined



66
67
68
69
70
71
72
73
74
75
# File 'lib/safe_ostruct.rb', line 66

def method_missing(method_name, *args, &_block)
  if method_name.end_with?("=")
    # Handle dynamic assignment
    attr_name = method_name[0...-1].to_sym
    @attributes[attr_name] = args.first
  else
    # Handle dynamic retrieval, return nil if attribute does not exist
    @attributes[method_name]
  end
end

Instance Method Details

#[](key) ⇒ Object?

Access attributes using [] with symbol or string

Parameters:

  • key (Symbol, String)

    the key for the attribute to be retrieved

Returns:

  • (Object, nil)

    the value of the attribute, or nil if undefined



81
82
83
# File 'lib/safe_ostruct.rb', line 81

def [](key)
  @attributes[key.to_sym]
end

#[]=(key, value) ⇒ Object

Set attributes using [] with symbol or string

Parameters:

  • key (Symbol, String)

    the key for the attribute to be set

  • value (Object)

    the value to assign to the attribute



89
90
91
# File 'lib/safe_ostruct.rb', line 89

def []=(key, value)
  @attributes[key.to_sym] = value
end

#delete_field(key) ⇒ Object?

Deletes an attribute from the struct.

Parameters:

  • key (Symbol, String)

    the key of the attribute to delete

Returns:

  • (Object, nil)

    the value of the deleted attribute, or nil if the attribute did not exist



106
107
108
# File 'lib/safe_ostruct.rb', line 106

def delete_field(key)
  @attributes.delete(key.to_sym)
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Ensures SafeOstruct responds to methods for defined and dynamically assigned attributes.

Parameters:

  • method_name (Symbol)

    the name of the method being checked

  • include_private (Boolean) (defaults to: false)

    whether to include private methods in the check

Returns:

  • (Boolean)

    true if the method is defined or dynamically assigned, otherwise false



98
99
100
# File 'lib/safe_ostruct.rb', line 98

def respond_to_missing?(method_name, include_private = false)
  @attributes.key?(method_name) || super
end

#to_hHash

Converts the attributes of the SafeOstruct into a hash.

and values are the corresponding attribute values. This method provides a way to easily access the internal state of the SafeOstruct as a standard hash, facilitating serialization and interoperability with other Ruby classes and methods that expect a hash input.

Returns:

  • (Hash)

    a hash representation of the attributes, where keys are symbols



117
118
119
# File 'lib/safe_ostruct.rb', line 117

def to_h
  @attributes
end