Class: CommandResultStruct
Overview
Option 3: Using Struct with dynamic extension
Class Method Summary collapse
Class Method Details
.new(**attributes) ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/command_result_alternatives.rb', line 99 def self.new(**attributes) # Create a Struct class with the given attributes plus defaults defaults = { exit_status: 0, stdout: '' } all_attrs = defaults.merge(attributes) struct_class = Struct.new(*all_attrs.keys, keyword_init: true) do def failure? !success? end def success? exit_status.zero? end # Intercept specific setter def new_lines=(value) warn caller.deref[0..4], value super(value) end # Add dynamic attribute support def method_missing(name, *args) if name.to_s.end_with?('=') # Add new attribute dynamically by recreating struct attr_name = name.to_s.chomp('=').to_sym current_attrs = to_h current_attrs[attr_name] = args.first # This is a limitation - we can't easily add new fields to existing Struct # So this approach has constraints super else super end end end struct_class.new(**all_attrs) end |