To convert a
.pem certificate to .pfx, ensure you have OpenSSL installed and have your .pem certificate file, private key file, and optionally a CA chain file ready.Use the command:
TILs
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.
.pem certificate to .pfx, ensure you have OpenSSL installed and have your .pem certificate file, private key file, and optionally a CA chain file ready.Member model where each user has a specific number of coins. When performing operations like capturing or deducting coins, we want to validate:dry-validation gem)Ruby
class CoinsValidator < Dry::Validation::Contract
params do
required(:user).filled(:integer)
required(:coins).filled(:integer, gt?: 0)
end
rule(:user) do
member = Member.find_by(unique_id: value) // querying database for member details
key.failure("does not exist") if member.nil?
end
rule(:coins, :user) do
member = Member.find_by(unique_id: values[:user]) // querying database for member details
if member && member.coins < values[:coins]
key(:coins).failure("are insufficient")
end
end
endMember object once in the :user rule and again in the :coins rule. This redundant querying increases database load and slows down validation, especially in high-traffic applications.Member object using the values hash provided by the dry-validation gem. The values hash allows us to store intermediate results, making them accessible to other validation rules.Ruby
class CoinsValidator < Dry::Validation::Contract
params do
required(:user).filled(:integer)
required(:coins).filled(:integer, gt?: 0)
end
rule(:user) do
values[:member] = Member.find_by(unique_id: value) // Caching the member object
key.failure("does not exist") if values[:member].nil?
end
rule(:coins) do
member = values[:member] // accessing the cached Member from values[:member] rather than querying the database again.
if member && member.coins < value
key.failure("are insufficient")
end
end
endsetTimeout or setInterval, Jest's timer mocking lets you fast-forward time.jest.useFakeTimers()Code
jest.useFakeTimers();
test("delayed greeting is sent after 3 seconds", () => {
const callback = jest.fn();
setTimeout(() => callback("Hello!"), 3000);
jest.runAllTimers();
expect(callback).toHaveBeenCalledWith("Hello!");
});attr_reader and attr_accessor are used to create getter and setter methods for class attributes. These are part of a group of methods (attr_* methods) that make it easier to create getter and setter methods for class attributes.attr_reader: Creates a getter method, allowing read-only access to an instance variable.Ruby
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtainattr_accessor: Creates both getter and setter methods, allowing read and write access to an instance variable.Ruby
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
person = Person.new("Sibtain")
puts person.name # Outputs: Sibtain
person.name = "John"
puts person.name # Outputs: Johnattr_reader and attr_accessor promotes encapsulation by controlling how the attributes of a class are accessed and modified.useFieldArray hook in react-hook-form -------------------------useFieldArray hook is part of react-hook-form and is used for handling dynamic fields in forms, such as arrays of inputs that can be added or removed dynamically.useFieldArray is the ideal solution to manage that dynamic behaviour without manually managing the state of each individual field.useFieldArray works:fields: An array of objects, where each object represents a field in the array.append: A function to add new fields to the array.remove: A function to remove fields from the array.update: A function to update an individual field in the array.JavaScript
import { useForm, useFieldArray } from "react-hook-form";
function DynamicForm() {
const { register, control, handleSubmit, formState: { errors } } = useForm({
defaultValues: {
questions: [{ question: "" }],
},
});
// UseFieldArray to handle the questions array dynamically
const { fields, append, remove } = useFieldArray({
control,
name: "questions", // Name of the array in the form's state
});
const onSubmit = (data: any) => {
console.log(data); // Submitting form data with dynamic fields
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{fields.map((item, index) => (
<div key={item.id}>
<input
{...register(`questions.${index}.question`)} // Register each question dynamically
defaultValue={item.question} // Set default value for each item in the array
/>
{errors.questions?.[index]?.question && (
<span>{errors.questions[index]?.question.message}</span>
)}
<button type="button" onClick={() => remove(index)}>Remove</button>
</div>
))}
<button type="button" onClick={() => append({ question: "" })}>
Add Question
</button>
<button type="submit">Submit</button>
</form>
);
}name: The name prop in useFieldArray points to the field array in your form state (in this case, questions).fields: This array holds the current data of the dynamic fields. Each item corresponds to a field in the form array.append: This method is used to add a new item to the array. You can pass the new data for the item when appending.remove: This method is used to remove an item by its index.useFieldArray:title and description).react-hook-form to handle validations and form submission.chat.deleteScheduledMessage API allows you to delete messages that were scheduled using chat.scheduleMessage but have not yet been sent.JavaScript
const response = await slackClient.chat.deleteScheduledMessage({
channel: channelId, {// ID of the channel where the message was scheduled }
scheduled_message_id: scheduledMessageId, {// ID of the scheduled message to delete}
});Ruby
require 'webmock/webmock_api.rb'
config.before(:each) do
stub_request(:any, /domain_name/).to_rack(WebmockApi
endRuby
# spec/fixtures/member_api_success.json
[
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"phone": "123-456-7890",
"membership_type": "Gold",
"status": "active"
},
{
"id": 2,
"name": "Jane Smith",
"email": "[email protected]",
"phone": "987-654-3210",
"membership_type": "Silver",
"status": "inactive"
}
]Ruby
class WebmockApi
SPEC_FIXTURES_PATH = 'spec/fixtures'.freeze
MEMBERS_SUCCESS = File.read("#{SPEC_FIXTURES_PATH}/members_api_success.json").freeze
POSTS_SUCCESS = File.read("#{SPEC_FIXTURES_PATH}/posts_api_success.json").freeze
ERROR = File.read("#{SPEC_FIXTURES_PATH}/error.json").freeze
def self.call(env)
new.call(env)
end
def call(env)
action = env['REQUEST_METHOD']
path = env['PATH_INFO']
params = env['QUERY_STRING']
case path
when '/external_members_api_path'
params.include?('test_user') ? [ 200, {}, [ MEMBERS_SUCCESS ] ] : [ 500, {}, [ ERROR ] ]
when '/external_post_api_path'
params.include?('new_post') ? [ 200, {}, [ POSTS_SUCCESS ] ] : [ 500, {}, [ ERROR ] ]
end
end
endRuby
require 'rails_helper'
require 'webmock/rspec'
RSpec.describe "Members", type: :request do
describe "GET /members_search_path" do
context "when the members API call is successful" do
it "returns member details from the API" do
get "/external_members_api_path", params: { member: "test_user" }
expect(response).to have_http_status(:ok)
user = response.parsed_body["member"]
expect(["id"]).to eq("123456")
expect(user["name"]).to eq("abc")
end
end
context "when the members API call is successful" do
it "returns error message from the API" do
get "/external_members_api_path", params: { member: "unknown_user" }
expect(response).to have_http_status(:ok)
expect(response).to have_http_status(:internal_server_error)
error = response.parsed_body["error"]
expect(error).to eq("Something went wrong")
end
end
end
endchat.postMessage method with the thread_ts parameter. This parameter specifies the timestamp (ts) of the parent message you want to reply to, creating a thread.ts (timestamp) of the Parent Messagets value. You can retrieve it by fetching messages in the channel, or from the response of a previously sent message.thread_tsthread_ts in the chat.postMessage payload to post your message as a reply in the thread.TypeScript
import { WebClient } from "@slack/web-api";
const client = new WebClient("YOUR_SLACK_BOT_TOKEN");
async function sendThreadedMessage(channel: string, parent_ts: string, message: string) {
try {
// Post a new message as a reply in the thread
const response = await client.chat.postMessage({
channel,
text: message,
thread_ts: parent_ts, // This makes it a threaded message
});
} catch (error) {
console.error("Error sending threaded message:", error);
}
}
// Usage example
sendThreadedMessage("C123456789", "1688852910.123456", "This is a reply in the thread.");ts as the thread_ts for replies:TypeScript
async function sendMessageWithThread(channel: string, message: string, replyMessage: string) {
try {
// Send the parent message
const parentMessage = await client.chat.postMessage({
channel,
text: message,
});
// Reply to the message in a thread
await client.chat.postMessage({
channel,
text: replyMessage,
thread_ts: parentMessage.ts,
});
} catch (error) {
console.error("Error sending messages:", error);
}
}
// Usage example
sendMessageWithThread("C123456789", "This is the main message", "This is a reply in the thread.");<template> elements is a cleaner and more maintainable approach.JavaScript
// In your stimulus controller
updateList() {
this.listTarget.innerHTML = `
<div class="flex gap-2">
<span>${this.name}</span>
<button>Delete</button>
</div>
`
}JavaScript
// In your view
<template data-list-target="template">
<div class="flex gap-2">
<span data-placeholder="name"></span>
<button>Delete</button>
</div>
</template>
// In your Stimulus controller
updateList() {
const template = this.templateTarget.content.cloneNode(true)
template.querySelector('[data-placeholder="name"]').textContent = this.name
this.listTarget.appendChild(template)
}set_variant method along with mobile-specific templates like index.html+mobileRuby
def set_variant
browser = Browser.new(request.user_agent)
if browser.device.mobile?
request.variant = :mobile
else
request.variant = :desktop
end
endindex.html.erb view, we can create a mobile-specific version by adding +mobile to the filename.Ruby
app/views/orders/index.html.erb
app/views/orders/index.html+mobile.erbuseFetch is a Nuxt composable used to fetch data in a server-side or client-side context, ensuring data is fetched before rendering the component. It is primarily used for making HTTP requests and providing a reactive way of managing the fetched data.useAsyncData is very similar to useFetch, but it allows for fetching data asynchronously, without blocking the server-side rendering process. It's useful when you want to fetch data in a non-blocking way, enabling the page to render without waiting for the data.useFetch fetches data synchronously during SSR, blocking the rendering process until the data is available.useAsyncData fetches data asynchronously, allowing the page to render without waiting for the data.form_with url: ...) or with a model (using form_with model: ...).form_with url: ...)Ruby
<%= form_with url: some_path, method: :post do |form| %>
<%= form.text_field :some_field %>
<%= form.submit "Submit" %>
<% end %>form_with_url is suitable for forms that don't map directly to a model, like search forms, login forms, or other custom actions etc.form_with model: ...)Ruby
<%= form_with model: @record do |form| %>
<%= form.text_field :name %>
<%= form.submit %>
<% end %>@record.new_record? is true, Rails generates a POST request to the model’s create route.@record.persisted? is true, Rails generates a PATCH request to update the model’s update route.form_with_model is suitable for forms that directly interact with a model, such as forms for creating or editing a resource (like User, Post, etc.).AWS Cognito and set it as permanent, we can use the AWS CLI with the following admin command:Code
aws cognito-idp admin-set-user-password \\
--user-pool-id <pool-id> \\
--username <cognito-username> \\
--password <password> \\
--permanentquery key can have its default values and can be set by following ways:defaultOptions object to query client as global defaults.Code
const queryClient = new QueryClient(
defaultOptions: {
queries: {
staleTime: 10 * 1000
}
}
}Fuzzy Matching by setQueryDefaults methodCode
queryClient.setQueryDefaults(
['todos','list'],
{staleTime: 10 * 1000}
)
//This sets default stale time of 10secs for all the matched queries having keys 'todos' and 'list'Code
useQuery({
queryKey: ['todo'],
staleTime: 10 * 1000,
});status: Either "fulfilled" or "rejected".value: The resolved value (if fulfilled) or reason: The rejection reason (if rejected).JavaScript
const promises = [
Promise.resolve(1),
Promise.reject('Error'),
Promise.resolve(2),
];
Promise.allSettled(promises).then((results) => {
results.forEach((result) => {
if (result.status === 'fulfilled') {
console.log('Result:', result.value);
} else {
console.log('Error:', result.reason);
}
});
});
Output :
Result: 1
Error: Error
Result: 2main branch into your current branch by creating a merge commit that combines the histories of both branches.main branch, making it look as if your work was started from the latest main commit..includes method to eager-load associated records, which reduces the number of database calls.Order and Item, where an Order has many Items. Without eager-loading, querying each order’s items individually would lead to N+1 queries.Ruby
orders = Order.all
orders.each do |order|
puts order.items # Each order triggers a separate query for items
end.includes, Rails will fetch all associated items in a single additional query:Ruby
orders = Order.includes(:items)
orders.each do |order|
puts order.items # No extra query is triggered here
endOrder records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.before_action runs a specified method before the controller action. It’s useful for tasks that need to happen before executing the main action, such as authentication, setting up a resource, or ensuring permissions.after_action runs a specified method after the controller action has executed. It’s useful for tasks that need to happen after the response is rendered, such as logging activity, tracking metrics, or cleaning up resources.Ruby
class PointsController < ApplicationController
before_action :set_user_points, only: [:show, :redeem]
after_action :update_points_history, only: [:redeem]
def show
# Show points balance
end
def redeem
# Redeem points logic
end
private
def set_user_points
@points = current_user.points
end
def update_points_history
# Log the points redemption action
end
endset_user_points will execute before the controller actions show and redeem. update_points_history will execute after the redeem action.onDelete: Cascade in Prisma automatically deletes the child records when a parent record is deleted.Code
model User {
id Int @id @default(autoincrement())
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}Code
await prisma.user.delete({ where: { id: 123 } })Code
git checkout branch-nameCode
git rebase -i HEAD~3Code
pick 7f9d4bf first commit
pick 3f8e810 second commit
pick ec48d74 third commitpick means to keep the commit as is.pick to squash / s for those commits.Code
# This is a combination of 3 commits.
# The first commit message:
fix for bug
# Commit message for #2:
Updated this
# Commit message for #3:
Added comments & updated READMEShowing page 7 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.
Don't worry. We've got you covered.
Start with the audit.