- Published
- Author
- Mohammad
```
pagy_array
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.
each_with_object is an enumerable method in Ruby that allows you to iterate over a collection while building up an object (like an array or hash). Unlike map, which creates a new array, each_with_object lets you modify an existing object in a single pass.collection.each_with_object(initial_object) do |item, object|
# Modify the object inside the block
endcollection: The array or enumerable you're iterating over.initial_object: The object that will be modified (e.g., {} for a hash or [] for an array).item: The current element in the iteration.object: The object that accumulates the results.each_with_object with a Hashnumbers = [1, 2, 3, 4, 5]
squares = numbers.each_with_object({}) do |num, hash|
hash[num] = num**2
end
puts squares
# Output: {1=>1, 2=>4, 3=>9, 4=>16, 5=>25}each_with_object?{} before the loop.collection_select when you need to populate a dropdown with a collection of ActiveRecord objects. It is built on top of select and provides a convenient way to display object attributes instead of a simple array of strings.select is used for manually defining options, typically from an array of strings or key-value pairs.collection_select is specifically designed for selecting records from an ActiveRecord collection, making it useful when working with database associations.lib/tasks directory..rake file in lib/tasks/ touch lib/tasks/custom_tasks.rakenamespace :custom do
desc "Say hello from a custom rake task"
task :hello do
puts "Hello from custom Rake task!"
end
endbin/rake custom:hello:environment if your task interacts with the database or modelsinverse_of option in ActiveRecord helps Rails recognize bidirectional associations in memory, reducing redundant database queries.class Employee < ApplicationRecord
belongs_to :department, foreign_key: 'department_code', primary_key: 'code', inverse_of: :employees
end
class Department < ApplicationRecord
has_many :employees, foreign_key: 'department_code', primary_key: 'code', inverse_of: :department
endinverse_of?inverse_of, Rails may reload the association unnecessarily:employee = Employee.first
department = employee.department # Triggers a SQL query
department.employees.include?(employee) # Without `inverse_of`, this could trigger another queryinverse_of, Rails avoids the extra query because it knows department.employees already includes employeedry-validation contracts, values is a hash containing all the parameters being validated. When defining rule blocks, you can access specific parameters using hash-like syntax.class MyContract < Dry::Validation::Contract
params do
required(:category).filled(:string)
end
rule(:category) do
key.failure("is not allowed") unless values[:category] == "approved_value"
end
endvalues holds all input parameters.values[:key] to access specific parameters inside rule blocks.payload = {
id: 123,
name: "Sample Item",
status: "processed",
timestamp:
Time.now.to_i
}
Karafka.producer.produce_sync(
topic: "your_topic_name",
payload: payload.to_json
)produce_sync ensures the message is sent before proceeding.topic specifies the Kafka topic where the message will be published.payload should be serialized into JSON or another supported format.Paris is the capital of France, known for the Eiffel Tower.Paris is the capital of France, known for the Eiffel Tower.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",
},
});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
}
}
})# 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
endlet(:admin_user) { create(:user, :admin) }
let(:guest_user) { create(:user, :guest) }
let(:confirmed_user) { create(:user, :confirmed) }public_send allows calling a method dynamically when its name is stored in a variable.public_send?quantity_field = item.respond_to?(:ordered_quantity) ? :ordered_quantity : :quantity
new_quantity = item.public_send(quantity_field).to_i + item_case[:quantity].to_iitem has ordered_quantity, it calls item.ordered_quantityitem.quantityif-else statements:) – Creates a Literal Symbol Keyitem.update!(
ordered_quantity: new_quantity,
):ordered_quantity).=>) – Evaluates the Left-Hand Side as a Keyitem.update!(
quantity_field => new_quantity,
)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
)quantity_field is determined dynamically based on the model, so => must be used instead of :.=>?: when the key is static and always the same.=> when the key is stored in a variable or needs to be evaluated dynamically.attr_reader automatically creates a getter method for instance variables, making code cleaner and more concise. Instead of writing:def some_number
@some_number
endattr_reader :some_numberimport { 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
}
}'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>
);
}page.execute_script("arguments[0].scrollIntoView(true)", button)scroll_to(button) # Scrolls to the elementlocaleCompare with { sensitivity: "base" } to compare strings without considering case or accents."Test".localeCompare("test", undefined, { sensitivity: "base" }) === 0; // ✅ True
"café".localeCompare("cafe", undefined, { sensitivity: "base" }) === 0; // ✅ True
"Hello".localeCompare("HELLO", undefined, { sensitivity: "base" }) === 0; // ✅ TruetoLowerCase() hacks anymore! 🎉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."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" != "heexpect(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 disabled_partial.html.erb), we might pass local variables to customize the rendering. However, if we try to use a local variable that wasn't passed, Rails will raise an error.local_assigns is a special hash that helps check if a local variable was provided when rendering the partial. Instead of directly using <%= show_projects %>, which could cause an error if missing, we can safely check local_assigns[:show_projects] first.<% if local_assigns[:show_projects] %>
<div class="flex">
<%= (render @user.projects) || (render 'shared/empty_state', message: "No projects found!") %>
</div>
<% end %>Showing page 5 of 42
AI is everywhere but it's unclear which investments will actually move your metrics and which are expensive experiments.
Most AI projects fail at the data layer. Pipelines, quality, access all need work before LLMs can deliver value.
Your engineers are shipping product. They don't have capacity to also become AI specialists with production-grade experience.
Aging, undocumented codebases make AI integration slow, risky, and expensive. They need to move first.