Create a mother class

Hi guys, I have one question. Is it possible when I declare a new class, everytime I declare a new function, it run a specific command before running the implementation of the function, like a mother function ?

Easiest way would be to just call some private method as the first line of every method you add to the class. I don’t think there’s a real good way to automate this tho.

You can define an annotation and modify all mothods with it in the class.

annotation BeforeExecute; end

macro def_hook_with_preload
  {% for method in @type.methods %}
    {% if method.annotation(BeforeExecute) %}
      # Redefine annotated method with preprocessing
      def {{method.name}}({{method.args.splat}})
        preprocess_string_data # Execute preprocessing hook
        previous_def # Call original method logic
      end
    {% end %}
  {% end %}
end

I generated the following instance with the help of deepseek:

class TextProcessor
  @original_text : String = ""
  @modified_text : String = ""

  # Annotation marks methods requiring preprocessing
  @[BeforeExecute]
  def replace_substrings(target : String, replacement : String)
    # Case-insensitive replacement using regex
    @modified_text = @original_text.gsub(/#{target}/i, replacement)
  end

  # Method without annotation remains unchanged
  def uppercase_transform
    @modified_text = @original_text.upcase
  end

  # Trigger macro processing at class finalization
  def_hook_with_preload

  private def preprocess_string_data
    # Demonstration of multiple string modification techniques:

    # 1. Remove leading/trailing whitespace
    @original_text = @original_text.strip

    # 2. Handle null input scenario
    @original_text = "DEFAULT_TEXT" if @original_text.empty?

    # 3. Preserve original state for processing
    @modified_text = @original_text.dup

    puts "Preprocessing completed: #{Time.utc}"
  end

  # Text initialization and display methods
  def initialize(input : String)
    @original_text = input
  end

  def display_results
    puts <<-OUTPUT
    Original: #{@original_text}
    Modified: #{@modified_text}
    OUTPUT
  end
end

# Execution Example
processor = TextProcessor.new("  ThIs Is tEsT tExT. th:pattern  ")
processor.replace_substrings("th", "THE")
processor.display_results

# Sample Output:
# Preprocessing completed: 2025-04-10 08:30:45 UTC
# Original: ThIs Is tEsT tExT. th:pattern
# Modified: THEIs Is tEsT tExT. THE:pattern

# Additional string modification demo
processor.uppercase_transform
processor.display_results

One known problem is that the annotation seems to be ineffective for block methods.