At Codemancers, we believe every day is an opportunity to grow. This section is where our team shares bite-sized discoveries, technical breakthroughs and fascinating nuggets of wisdom we've stumbled upon in our work.
Mohammad
Traits in FactoryBot allow you to define reusable pieces of attributes that can be mixed into factories to create variations of objects without duplicating code.
Code
FactoryBot.define do factory :user do name { "John Doe" } trait :admin do role { "admin" } end endendcreate(:user, :admin)
Here, :admin is a trait that overrides or adds attributes (role: "admin"). You can pass traits to create, build, or attributes_for to easily generate variations. #CU6U0R822 #RSpec
Swasthik
Boost Query Performance with Prisma's Rust-free Engine(v6.7.0+)
Picture-in-Picture (PiP) API – Enabling Floating Video Playback
The Picture-in-Picture (PiP) API enables developers to present an HTML <video> element in a small, floating, always-on-top window. This allows users to continue watching a video while interacting with other applications or browser tabs.
Key Concepts • video.requestPictureInPicture(): Initiates PiP mode for the video element. • document.exitPictureInPicture() : Exits PiP mode. • document.pictureInPictureElement : Returns the element currently in PiP, or null. • Associated Events: ◦ enterpictureinpicture ◦ leavepictureinpicture
⚠️ Limitations • Only applicable to native <video> elements. • Most browsers require the video to be playing before entering PiP. • Must be triggered through a user gesture (e.g., a click). • Safari has limited support and relies on its own implementation. 🌐 Browser Support • Chrome • Edge • Opera • Firefox (with some restrictions) #CCT1JMA0Z
Sudeep
File Preview in React — Beyond Just Images Building a file preview system in React can surface several helpful patterns — especially when working with images, PDFs, media, and plain text files.
• You can preview any local file before upload using:
JavaScript
URL.createObjectURL(file)
It works seamlessly with: • Images • PDFs • Audio files • Videos • Plain text Tip: Always call URL.revokeObjectURL() when the preview is no longer needed to prevent memory leaks.
🔄Handling Local and Server Files Together To support previews for both uploaded and already-stored files, use a union type:
Then render conditionally based on file.type. Rendering Previews Based on File Type • <img> → for images • <iframe> → for PDFs or text files • <audio> / <video> → for media files #CCT1JMA0Z #react
Nitturu
📌 Using Alpine.js in Rails to Toggle Content Efficiently
You can use Alpine.js in a Rails app to handle simple UI interactions like showing, hiding, or toggling content — with zero overhead and great maintainability.
🧠 How it works: • Alpine adds lightweight reactivity directly in your HTML using attributes like x-data, @click, and x-show. • Clicking a button updates the type (or any reactive) value. • Alpine automatically re-evaluates all x-show (and related) bindings when that reactive value changes. • It then updates the UI by toggling styles like display: none, not by re-rendering or manipulating the DOM. • On clicking the "Urgent" button, Alpine applies display: none to the normal_partial and removes it from urgent_partial, effectively toggling visibility between the two. 💡 Example in Rails ERB:
• Both partials are rendered server-side on initial load • Alpine just toggles their visibility using CSS (e.g., display: none), it wont manipulate DOM. • No data loss or performance bottleneck — ideal for UI tab switching or inline modals ✅ Why it's great: • No page reloads or re-renders • No JavaScript DOM manipulation — just CSS toggling • Preserves state and DOM structure • Ideal for tabs, modals, section toggles, and lightweight UI #Rails #Alphine.js
Sudeep
Creating Google Calendar Events with NestJS
Integrating Google Calendar event creation in a NestJS backend can be done seamlessly using the googleapis package. Key Steps: • Set up OAuth2 with access and refresh tokens. • Use calendar.events.insert() to create events. • Always include the timeZone field to ensure accurate scheduling. Sample code:
Common Pitfalls: • Incorrect scopes → leads to permission denied errors. • Missing timeZone → causes unexpected event timings. • Expired tokens → results in 401 Unauthorized errors. #NestJS
Sudeep
Understanding ExecutionContext in NestJS Guards
Today I learned how ExecutionContext works in NestJS — it's a powerful tool for accessing low-level request details within Guards, Interceptors, and Custom Decorators. While building a custom AuthGuard, I used ExecutionContext to extract the request object and retrieve the authenticated user like so:
Code
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';@Injectable()export class AuthGuard implements CanActivate { canActivate(context: ExecutionContext): boolean { const request = context.switchToHttp().getRequest(); const user = request.user; return !!user; // or apply custom authorization logic }}
Why It Matters: • ExecutionContext wraps the current request lifecycle and gives you flexible access to request-specific information. • You can switch between different transport layers (HTTP, RPC, WebSockets) using methods like switchToHttp(), switchToRpc(), etc. • It's essential for building dynamic and context-aware logic in guards, interceptors, and decorators. Pro Tip: Use context.getClass() and context.getHandler() to access metadata about the controller and handler being executed — especially useful for implementing role-based access control or custom permission systems.
#CCT1JMA0Z #NestJS
Satya
the term Cannibalization in warehouse terms meaning taking components or parts from one unit (often damaged, unused, or scrapped) to use in repairing or completing another unit. In simple terms we can understand it as refubrished items where later the warehouse can send that to a buyer and then the buyer decide which store to sell these items in a discounted price.
#warehouse #outbound
Sudeep
JavaScript Temporal — A Modern Approach to Date & Time
Today I explored the Temporal API in JavaScript — a long-awaited, modern alternative to the built-in Date object. The traditional Date API is known for its limitations: it’s mutable, difficult to work with across time zones, and error-prone when performing date arithmetic. Temporal addresses these issues with a clean, consistent, and powerful API.
Key Advantages of Temporal • Immutable: All Temporal objects are immutable, avoiding side effects • Time zone-aware: Native support via ZonedDateTime • Consistent parsing & formatting • Clear duration handling with Temporal.Duration • More intuitive syntax — no more 0-based months Practical Examples
JavaScript
// Get current date-timeconst now = Temporal.Now.plainDateTimeISO();console.log(now.toLocaleString()); // "6/18/2025, 6:01:52 PM"// Time zone conversionconst nyMeeting = Temporal.ZonedDateTime.from('2025-06-18T10:00[America/New_York]');const kolkataTime = nyMeeting.withTimeZone('Asia/Kolkata');console.log(kolkataTime.toLocaleString()); // "6/18/2025, 7:30:00 PM GMT+5:30"
Why This Matters ? Whether you're building scheduling systems, handling international time zones, or performing complex date calculations — the Temporal API offers accuracy, clarity, and reliability that the current Date API lacks.
#CCT1JMA0Z
Nitturu
The difference between Active Model association call, joins and includes. Consider two tables: order_requests and orders, where each order_request has many orders.
1. order_request.orders • Purpose: You’re accessing the associated orders from a single order_request object. • Behavior: This will trigger a separate SQL query unless the association was already loaded (using includes).
Code
SELECT "orders".* FROM "orders" WHERE "orders"."order_request_id" = 123;
• Use Case: When you’re working with one order_request and want to fetch its orders.
2. order_requests.joins(:orders) • Purpose: Adds an INNER JOIN in the SQL between order_requests and orders. • Behavior: Doesn't load orders into memory, just uses them for filtering or sorting in SQL.
Code
SELECT "order_requests".*FROM "order_requests"INNER JOIN "orders" ON "orders"."order_request_id" = "order_requests"."id";
• Use Case: When you want to query order_requestsbased on conditions in orders (e.g., where(orders: { status: 'active' })), but don’t need to access orders in Ruby.
3. order_requests.includes(:orders) • Purpose: Performs eager loading via a LEFT OUTER JOIN + separate query, or just a separate query depending on ActiveRecord's optimization. • Behavior: Loads orders for each order_request to prevent N+1 queries when looping.
Code
SELECT "order_requests".* FROM "order_requests" WHERE ...SELECT "orders".* FROM "orders" WHERE "order_request_id" IN (1, 2, 3, ...)
• Use Case: When you plan to access order_request.ordersfor many records in a loop and want to avoid repeated SQL calls (N+1 issue).
#Rails
Sudeep
How Decorators Work in NestJS
Decorators in NestJS are a powerful way to attach metadata to routes, classes, or parameters. Today, I implemented a custom @Roles() decorator to control access to certain routes based on user roles.
This attaches metadata like roles = ['Admin'] to the route handler.
✅ Guard to Read Metadata
TypeScript
// roles.guard.ts@Injectable()export class RolesGuard implements CanActivate { constructor(private reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { const requiredRoles = this.reflector.get<string[]>( 'roles', context.getHandler() ); const request = context.switchToHttp().getRequest(); const user = request.user; return requiredRoles?.includes(user?.role); // Check if user has the role }}
✅Controller Usage
TypeScript
@UseGuards(RolesGuard)@Roles('Admin')@Patch(':id')updateOrg() { // This route is accessible only to users with the 'Admin' role}
Under the hood, decorators useReflect.defineMetadata to attach metadata, and NestJS’s Reflector service helps retrieve that metadata in guards or interceptors.
✅Takeaway: Custom decorators make your code cleaner, declarative, and easier to manage — especially when dealing with role-based access in multi-user systems.
#typescript #NestJs
Puneeth
Using emit in NestJS
In NestJS, event-based communication can be implemented using @nestjs/event-emitter package, which is built on top of eventemitter2 . It's particularly useful for decoupling the parts of our application — for example, sending notifications, logging, or triggering async jobs after certain actions.
How to use it?
• Install the necessary package:
Code
npm install --save @nestjs/event-emitter
• Register the module in the app:
Code
// app.module.tsimport { EventEmitterModule } from '@nestjs/event-emitter';@Module({ imports: [ EventEmitterModule.forRoot(), ],})export class AppModule {}
• Emit an event from anywhere in the app:
Code
// user.service.tsimport { EventEmitter2 } from '@nestjs/event-emitter';@Injectable()export class UserService { constructor(private eventEmitter: EventEmitter2) {} async createUser(userDto: CreateUserDto) { const user = await this.userRepository.save(userDto); this.eventEmitter.emit('user.created', user); // 🔥 return user; }}
• Handle the event using a listener:
Code
// user.listener.tsimport { OnEvent } from '@nestjs/event-emitter';@Injectable()export class UserListener { @OnEvent('user.created') handleUserCreatedEvent(payload: any) { console.log('User created!', payload); // Trigger welcome email, analytics, etc. }}
Why use emits?
✅ Decouples the core logic from side-effects ✅ Makes it easier to add/remove behaviours like notifications, logging ✅ Encourages modular architecture
#CCT1JMA0Z #nestJs #event_based_communication
Sudeep
Difference Between jest.fn() and jest.spyOn() in Jest
🧪 While writing tests in Jest, I came across two commonly used utilities: jest.fn() and jest.spyOn(). They may seem similar, but they serve different purposes:
🔹jest.fn() • Creates a new mock function from scratch • Ideal when you want to replace a function with a mock implementation entirely • Commonly used to inject mocked dependencies in unit tests
🔹jest.spyOn() • Spies on an existing method of an object • Allows you to observe calls to the method or mock its implementation, while retaining the original object structure
👉 Use jest.fn() when creating mocks from scratch. 👉 Use jest.spyOn() to observe or override existing methods.
#jest #CCT1JMA0Z #testing
Puneeth
Recover Lost Data in PostgreSQL
Most SQL databases, like PostgreSQL, let us restore the database to a specific point in time — this is called Point-In-Time Recovery (PITR). PostgreSQL makes this possible using something called the Write-Ahead Log (WAL).
The WAL keeps a log of every change made to the database, like adding, updating, or deleting the data. Each of these log has a unique ID called as Log Sequence Number (LSN). This allows PostgreSQL to rebuild the database exactly as it was at any moment in the past.
However, PostgreSQL doesn’t keep these logs forever. A background process automatically removes old WAL files when they’re no longer needed to save space.
#postgreSQL #databases
Sudeep
How to Revoke (Undo) a Git Rebase
If you’ve run a git rebase and need to undo it due to issues, here’s a simple way to revert back:
1.Check your reflog to find the commit before rebase started:
Code
git reflog
Look for the commit hash just before the rebase (usually marked with rebase started).
2.Reset your branch back to that commit:
Code
git reset --hard <commit-hash>
This will reset your branch to the exact state before the rebase.
Important: • Use git reset --hard with caution, as it will discard any uncommitted changes. #Git
Sudeep
React Query
✅ It simplifies data fetching, caching, syncing, and updating — without manually managing loading or error states. Here’s a small snippet I worked on today:
💡 What I love: • Built-in caching • Automatic background refetching • Easy-to-use API with powerful features #CCT1JMA0Z #FrontendDevelopment
Sudeep
Typescriptas const turns everything into readonly.
TypeScript
const user = { role: 'admin',} as const;user.role = 'editor'; // ❌ Error: Cannot assign to 'role' because it is a read-only property.
💡as const is great for making values literal and immutable — useful in Redux, Enums, etc.
#Typescript #CCT1JMA0Z
Sudeep
JavaScript: Object.groupBy()
Grouping data used to be messy — relying on Array.reduce() with verbose logic. But JavaScript's new Object.groupBy() method has made things incredibly elegant and easy!
With just one line, you can group array items based on any property. It’s clean, readable, and production-friendly.
✅ Cleaner. ✅ Less boilerplate. ✅ Much easier to read.
#CCT1JMA0Z #WebDevelopment
Vaibhav YadavSenior System Analyst
Using Makefile for tedious commands
A Makefile can be used to automate a commands, simplifying the execution process. Here’s a concise example:
Code
.PHONY: run-script# Target to run a long commandrun-script:\t@echo "Running a long command..."\tsleep 5 # Simulate a long-running command\t@echo "Command completed."
Running the Makefile 1. Create a Makefile: Save the above content as Makefile in your project directory. 2. Run Make: In your terminal, navigate to the project directory and execute:
Code
make run-script
Benefits • Simplicity: Easily run a long command without remembering the syntax. • Automation: Reduces manual effort and potential errors. #cli #automation #makefile #commands
Sudeep
💡Why is [] == ![] true in JavaScript?
It all comes down to type coercion and how JavaScript evaluates expressions using the == (abstract equality) operator.
Here’s the breakdown: ![] evaluates to false because an empty array is truthy, and the ! operator negates it. So the expression becomes: [] == false When comparing an object (like[]) to a boolean with==, JavaScript converts both sides to numbers: +[] → 0 +false → 0 So: