Fueling Curiosity, One Insight at a Time
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.
Mar 4, 2025
Updating Session in NextAuth
In NextAuth, you can update the session data using the
Assuming a
This updates the session without requiring a full reload, ensuring the UI reflects the changes immediately. 🚀
#next-auth #nextjs
In NextAuth, you can update the session data using the
update
function from useSession()
. Here's how you can modify user details dynamically:
const { data: session, update } = useSession();
await update({
user: {
...session?.user,
name: "Updated Name",
role: "editor",
},
});
Assuming a
strategy: "jwt"
is used, the update()
method will trigger a jwt
callback with the trigger: "update"
option. You can use this to update the session object on the server.
export default NextAuth({
callbacks: {
// Using the `...rest` parameter to be able to narrow down the type based on `trigger`
jwt({ token, trigger, session }) {
if (trigger === "update" && session?.name) {
// Note, that `session` can be any arbitrary object, remember to validate it!
token.name = session.name
token.role = session.role
}
return token
}
}
})
This updates the session without requiring a full reload, ensuring the UI reflects the changes immediately. 🚀
#next-auth #nextjs
Adithya Hebbar
System Analyst
Feb 25, 2025
Traits in FactoryBot helps to define reusable variations of a factory without creating multiple factories. They are useful when we need optional attributes or specific states in test data.
Let's say we have a User model with different roles (admin, regular, guest). Instead of writing separate factories, we can use traits like below:
And use it like below
#CU6U0R822 #factory_bot
Let's say we have a User model with different roles (admin, regular, guest). Instead of writing separate factories, we can use traits like below:
# spec/factories/users.rb
FactoryBot.define do
factory :user do
first_name { Faker::Name.first_name }
email { Faker::Internet.unique.email }
password { "password123" }
trait :admin do
role { "admin" }
end
trait :guest do
role { "guest" }
end
trait :confirmed do
confirmed_at { Time.current }
end
end
end
And use it like below
let(:admin_user) { create(:user, :admin) }
let(:guest_user) { create(:user, :guest) }
let(:confirmed_user) { create(:user, :confirmed) }
#CU6U0R822 #factory_bot
Puneeth kumar
System Analyst
Feb 25, 2025
In Ruby,
• Why Use
Instead of calling methods explicitly, we can determine the method name at runtime and call it dynamically.
Example: Handling Different Attribute Names
• If
• Otherwise, it calls
• This avoids unnecessary
#ruby
public_send
allows calling a method dynamically when its name is stored in a variable.• Why Use
public_send
?Instead of calling methods explicitly, we can determine the method name at runtime and call it dynamically.
Example: Handling Different Attribute Names
quantity_field = item.respond_to?(:ordered_quantity) ? :ordered_quantity : :quantity
new_quantity = item.public_send(quantity_field).to_i + item_case[:quantity].to_i
• If
item
has ordered_quantity
, it calls item.ordered_quantity
• Otherwise, it calls
item.quantity
• This avoids unnecessary
if-else
statements#ruby
Nived Hari
System Analyst
Feb 25, 2025
In Ruby, there are two ways to define hash keys:
1. Using the Colon Syntax (
Key Behavior: The key is treated as a fixed symbol (e.g.,
2. Using the Hash Rocket (
Key Behavior: The left-hand side is evaluated dynamically, making it useful for variable-based keys.
Example Use Case: Dynamic Keys
Here,
When to Use
• When working with multiple models that have different column names
• When dynamically generating hash keys at runtime
• When building flexible APIs that handle varying attribute names
Takeaway:
• Use
• Use
#ruby
1. Using the Colon Syntax (
:
) – Creates a Literal Symbol Key
item.update!(
ordered_quantity: new_quantity,
)
Key Behavior: The key is treated as a fixed symbol (e.g.,
:ordered_quantity
).2. Using the Hash Rocket (
=>
) – Evaluates the Left-Hand Side as a Key
item.update!(
quantity_field => new_quantity,
)
Key Behavior: The left-hand side is evaluated dynamically, making it useful for variable-based keys.
Example Use Case: Dynamic Keys
quantity_field = item.respond_to?(:ordered_quantity) ? :ordered_quantity : :quantity
new_quantity = item.public_send(quantity_field).to_i + item_case[:quantity].to_i
item.update!(
quantity_field => new_quantity, # Evaluates to :ordered_quantity or :quantity
)
Here,
quantity_field
is determined dynamically based on the model, so =>
must be used instead of :
.When to Use
=>
?• When working with multiple models that have different column names
• When dynamically generating hash keys at runtime
• When building flexible APIs that handle varying attribute names
Takeaway:
• Use
:
when the key is static and always the same.• Use
=>
when the key is stored in a variable or needs to be evaluated dynamically.#ruby
Nived Hari
System Analyst
Feb 20, 2025
In Ruby,
You can simply use:
This makes attributes read-only while keeping the class lightweight
#ruby #CU6U0R822
attr_reader
automatically creates a getter method for instance variables, making code cleaner and more concise. Instead of writing:
def some_number
@some_number
end
You can simply use:
attr_reader :some_number
This makes attributes read-only while keeping the class lightweight
#ruby #CU6U0R822
Nived Hari
System Analyst
Feb 20, 2025
Real-time AI response streaming improves user experience by reducing wait times and making interactions feel more dynamic. Instead of waiting for the entire response to be generated before displaying it, streaming allows data to be processed and presented incrementally.
Example of AI response streaming using Nest Js backend and Next JS front end.
Setting Up the NestJS Backend for Streaming AI Responses
Controller
How It Works
• The @Post('chat') endpoint listens for chat requests.
• The streamText function sends user messages to OpenAI and receives a streamed response.
• pipeDataStreamToResponse(res) directly streams the AI-generated content to the client as it arrives.
Building the Next.js Frontend for AI Response Streaming
chat/page.tsx
How It Works
• The useChat hook from AI-SDK manages state and streaming logic automatically.
• It sends user messages to the backend and updates the UI in real time as responses arrive.
• The messages array dynamically updates, displaying each chunk of AI-generated text as it's received.
#C08DPTN3JAW #streaming #next js #nest js
Example of AI response streaming using Nest Js backend and Next JS front end.
Setting Up the NestJS Backend for Streaming AI Responses
Controller
import { Controller, Post, Body, Res } from '@nestjs/common';
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import { Response } from 'express';
@Controller('orchestrator')
export class OrchestratorController {
@Post('chat')
async chat(@Body() payload: any, @Res() res: Response) {
const { messages } = payload;
const result = streamText({
model: openai('gpt-4o'),
messages,
});
result.pipeDataStreamToResponse(res); // Streams the AI response directly to the client
}
}
How It Works
• The @Post('chat') endpoint listens for chat requests.
• The streamText function sends user messages to OpenAI and receives a streamed response.
• pipeDataStreamToResponse(res) directly streams the AI-generated content to the client as it arrives.
Building the Next.js Frontend for AI Response Streaming
chat/page.tsx
'use client';
import { useChat } from '@ai-sdk/react';
export default function Home() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: 'https://localhost:3000/api/orchestrator/chat', // make the post request to the NestJS backend
});
return (
<div>
{messages.map((message) => (
<div key={message.id}>
{message.role === 'user' ? 'User: ' : 'AI: '}
{message.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
name="prompt"
value={input}
onChange={handleInputChange}
className="text-black"
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
How It Works
• The useChat hook from AI-SDK manages state and streaming logic automatically.
• It sends user messages to the backend and updates the UI in real time as responses arrive.
• The messages array dynamically updates, displaying each chunk of AI-generated text as it's received.
#C08DPTN3JAW #streaming #next js #nest js
Nitturu Baba
System Analyst
Feb 20, 2025
Collection caching is a way to speed up rendering multiple items on a page by storing their HTML in cache.
How it works:
1. When we use <%= render partial: 'products/product', collection: @products, cached: true %>, Rails checks if each product's HTML is already stored in the cache.
2. If a product’s HTML is found in the cache, Rails loads it quickly instead of rendering it again.
3. If a product’s HTML is not in the cache, Rails will render it, store it in the cache, and use it next time.
4. The big advantage: Rails fetches all cached products at once (instead of one by one), making it much faster.
#CU6U0R822 #caching #collection_caching
How it works:
1. When we use <%= render partial: 'products/product', collection: @products, cached: true %>, Rails checks if each product's HTML is already stored in the cache.
2. If a product’s HTML is found in the cache, Rails loads it quickly instead of rendering it again.
3. If a product’s HTML is not in the cache, Rails will render it, store it in the cache, and use it next time.
4. The big advantage: Rails fetches all cached products at once (instead of one by one), making it much faster.
#CU6U0R822 #caching #collection_caching
Puneeth kumar
System Analyst
Feb 19, 2025
When testing with Capybara, you might need to scroll an element into view before interacting with it. Instead of using JavaScript like:
You can use Capybara's built-in method:
This is available in
Capybara 3.26+
and is the preferred way to ensure visibility before clicking or interacting with an element.
#capybara #CU6U0R822 #C041BBLJ57G
page.execute_script("arguments[0].scrollIntoView(true)", button)
You can use Capybara's built-in method:
scroll_to(button) # Scrolls to the element
This is available in
Capybara 3.26+
and is the preferred way to ensure visibility before clicking or interacting with an element.
#capybara #CU6U0R822 #C041BBLJ57G
Nived Hari
System Analyst
Feb 19, 2025
In JavaScript, you can use
Example:
• Case-insensitive
• Accent-insensitive
No need for
second argument is
Sensitivity is the behaviour of the comparison
#stimulus #JavaScript #StringComparison
localeCompare
with { sensitivity: "base" }
to compare strings without considering case or accents.Example:
"Test".localeCompare("test", undefined, { sensitivity: "base" }) === 0; // ✅ True
"café".localeCompare("cafe", undefined, { sensitivity: "base" }) === 0; // ✅ True
"Hello".localeCompare("HELLO", undefined, { sensitivity: "base" }) === 0; // ✅ True
• Case-insensitive
• Accent-insensitive
No need for
toLowerCase()
hacks anymore! 🎉second argument is
locale
. by giving it as "Undefined" it uses default locale of the runtime environment. We can specify as "en", "id" etc. It is used in sorting scenarios ig.Sensitivity is the behaviour of the comparison
"base" → Ignores case & accents ("café" == "cafe", "Hello" == "hello")
"accent" → Considers accents but ignores case ("café" != "cafe", "Hello" == "hello")
"case" → Considers case but ignores accents ("café" == "cafe", "Hello" != "hello")
"variant" → Considers both case & accents ("café" != "cafe", "Hello" != "he
#stimulus #JavaScript #StringComparison
Nived Hari
System Analyst
Feb 19, 2025
By default, Capybara only finds visible and interactable elements. If a button is disabled or outside the viewport, Capybara may fail to locate it.
To fix this, use:
•
•
This is useful when testing UI behaviors where buttons are conditionally enabled/disabled or require scrolling to be visible.
#CU6U0R822 #capybara #C041BBLJ57G #specs
To fix this, use:
expect(page).to have_button("Add Discrepancy", disabled: true, visible: :all)
•
disabled: true
ensures the button is actually disabled •
visible: :all
allows Capybara to find buttons that are hidden, off-screen, or disabledThis is useful when testing UI behaviors where buttons are conditionally enabled/disabled or require scrolling to be visible.
#CU6U0R822 #capybara #C041BBLJ57G #specs
Nived Hari
System Analyst
Showing 4 to 5 of 77 results
Ready to Build Something Amazing?
Codemancers can bring your vision to life and help you achieve your goals
- Address
2nd Floor, Zee Plaza,
No. 1678, 27th Main Rd,
Sector 2, HSR Layout,
Bengaluru, Karnataka 560102 - Contact
hello@codemancers.com
+91-9731601276