Class: CommandResultInstanceVars
- Defined in:
- lib/command_result_alternatives.rb
Overview
Option 2: Using instance variables with define_method
Instance Method Summary collapse
- #failure? ⇒ Boolean
-
#initialize(**attributes) ⇒ CommandResultInstanceVars
constructor
A new instance of CommandResultInstanceVars.
- #method_missing(name, *args) ⇒ Object
-
#new_lines=(value) ⇒ Object
Intercept specific setter.
- #respond_to_missing?(name, include_private = false) ⇒ Boolean
- #success? ⇒ Boolean
Constructor Details
#initialize(**attributes) ⇒ CommandResultInstanceVars
Returns a new instance of CommandResultInstanceVars.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/command_result_alternatives.rb', line 35 def initialize(**attributes) @exit_status = 0 @stdout = '' attributes.each do |name, value| instance_variable_set("@#{name}", value) # Define getter and setter methods dynamically self.class.define_method(name) do instance_variable_get("@#{name}") end self.class.define_method("#{name}=") do |val| instance_variable_set("@#{name}", val) end end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/command_result_alternatives.rb', line 67 def method_missing(name, *args) if name.to_s.end_with?('=') # Setter attr_name = name.to_s.chomp('=') instance_variable_set("@#{attr_name}", args.first) # Define methods for future use self.class.define_method(attr_name) do instance_variable_get("@#{attr_name}") end self.class.define_method(name) do |val| instance_variable_set("@#{attr_name}", val) end else # Getter if instance_variable_defined?("@#{name}") instance_variable_get("@#{name}") else super end end end |
Instance Method Details
#failure? ⇒ Boolean
53 54 55 |
# File 'lib/command_result_alternatives.rb', line 53 def failure? !success? end |
#new_lines=(value) ⇒ Object
Intercept specific setter
62 63 64 65 |
# File 'lib/command_result_alternatives.rb', line 62 def new_lines=(value) warn caller.deref[0..4], value @new_lines = value end |
#respond_to_missing?(name, include_private = false) ⇒ Boolean
91 92 93 94 |
# File 'lib/command_result_alternatives.rb', line 91 def respond_to_missing?(name, include_private = false) attr_name = name.to_s.chomp('=').to_sym instance_variable_defined?("@#{attr_name}") || super end |
#success? ⇒ Boolean
57 58 59 |
# File 'lib/command_result_alternatives.rb', line 57 def success? exit_status.zero? end |