How to access static properties in an object in Ruby

1 Answer

0 votes
class Configuration
  # Define a class instance variable (acts as our static property).
  # This variable belongs directly to the Configuration class object, 
  # not to any instance of the class.
  @environment = "production"

  # Class method to safely read the static property (acting as a static getter)
  def self.environment
    @environment
  end

  # Class method to safely modify the static property with validation (acting as a static setter)
  def self.environment=(new_env)
    if new_env.is_a?(String) && !new_env.strip.empty?
      @environment = new_env
    end
  end

  # A class method that utilizes the static property
  def self.get_environment_details()
    "Active environment status: #{@environment}"
  end
end

# --- Example Usage ---

# 1. Accessing the static property/method directly via the Class Name (Best Practice)
puts "Current Environment: #{Configuration.environment}"
puts Configuration.get_environment_details()

# 2. Modifying the static property using the class setter method
Configuration.environment = "staging"
puts "Updated Environment: #{Configuration.environment}"


# Note on Instances:
# config_instance = Configuration.new
# config_instance.environment # Raises a NoMethodError! 
# Instances cannot access class-level static properties directly.


# run:
# 
# Current Environment: production
# Active environment status: production
# Updated Environment: staging
# 

 



answered 6 days ago by avibootz
...