Applying Data Filtering and Aggregation in a User Management System
Introduction
Welcome to today’s lesson on applying data filtering and aggregation in a real-world scenario through a user management system. We’ll start by building a foundational structure that can handle basic user operations, then gradually expand it by introducing more advanced functionalities to allow filtering and aggregating user data.
Starter Task Methods
In our starter task, we’ll implement a class to manage basic operations on a collection of user data, specifically handling the addition of new users, retrieving user profiles, and updating existing user profiles. Here are the methods we’ll begin with:
- add_user(user_id, age, country, subscribed) — Adds a new user with specified attributes. Returns
trueif the user is added successfully; returnsfalseif a user with the sameuser_idalready exists. - get_user(user_id) — Retrieves the user’s profile as a hash if the user exists; returns
nilif the user does not exist. - update_user(user_id, age = nil, country = nil, subscribed = nil) — Updates the user’s profile with provided parameters. Returns
trueif the user exists and was updated, andfalseotherwise.
Implementing Basic User Management
Let’s begin by creating a UserManager class that manages user data within a hash structure, @users, where each key is a user_id and each value is a hash representing the user’s profile.
The initialize method sets up an empty hash, @users, which will store all user profiles.
Adding and Retrieving Users
The add_user and get_user methods handle adding new users and retrieving existing user profiles.
In add_user, we check if a user with the specified user_id already exists. If not, we create a new entry in @users with the user’s details and return true. If the user already exists, it returns false. The get_user method retrieves a user’s profile from @users, returning the profile if found or nil if the user does not exist.
