0
0
Rubyprogramming~30 mins

Why hooks enable framework building in Ruby - See It in Action

Choose your learning style9 modes available
Why hooks enable framework building
📖 Scenario: Imagine you are creating a simple event system in Ruby where different parts of a program can react to certain events. This is like setting up hooks where you can attach your own code to run when something happens.
🎯 Goal: You will build a basic event hook system that allows registering and running hooks. This shows how hooks help frameworks let users add custom behavior easily.
📋 What You'll Learn
Create a hash called hooks to store event names and their attached blocks
Create a method called register_hook that takes an event name and a block, and stores the block in hooks
Create a method called run_hook that takes an event name and runs all blocks attached to that event
Demonstrate registering two hooks for the event :start and then running them
💡 Why This Matters
🌍 Real World
Many frameworks use hooks to let users add their own code at key points, like when a web request starts or finishes.
💼 Career
Understanding hooks helps you build or use frameworks that are flexible and customizable, a key skill in software development.
Progress0 / 4 steps
1
Create the hooks storage
Create a hash called hooks and set it to an empty hash {}.
Ruby
Need a hint?

Use hooks = {} to create an empty hash.

2
Create the register_hook method
Create a method called register_hook that takes two parameters: event and a block. Inside the method, add the block to the hooks hash under the key event. Initialize the key with an empty array if it does not exist.
Ruby
Need a hint?

Use hooks[event] ||= [] to create an array if needed, then add the block with << block.

3
Create the run_hook method
Create a method called run_hook that takes one parameter event. Inside the method, check if hooks[event] exists, then call each block stored there using call.
Ruby
Need a hint?

Use hooks[event].each { |hook| hook.call } to run each block.

4
Register and run hooks
Register two hooks for the event :start using register_hook. The first hook should print "First start hook" and the second should print "Second start hook". Then call run_hook(:start) to run them.
Ruby
Need a hint?

Use register_hook(:start) { puts "First start hook" } and similar for the second hook, then run_hook(:start).