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.
Nov 7, 2024
SEND SLACK MESSAGE AS A THREAD
To send a message as a thread in Slack using the Slack API, we can use the
Here’s how to send a threaded message:
1. Get the
• If you’re replying to a specific message, you’ll need its
2. Send a Threaded Message Using
• Use
Example:-
If we don't have any parent message then,we can first send a message and then use its
#C04A9DMK81E #slack #slackapi #thread
To send a message as a thread in Slack using the Slack API, we can use the
chat.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.Here’s how to send a threaded message:
1. Get the
ts (timestamp) of the Parent Message• If you’re replying to a specific message, you’ll need its
ts value. You can retrieve it by fetching messages in the channel, or from the response of a previously sent message.2. Send a Threaded Message Using
thread_ts• Use
thread_ts in the chat.postMessage payload to post your message as a reply in the thread.Example:-
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.");If we don't have any parent message then,we can first send a message and then use its
ts as the thread_ts for replies:
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.");#C04A9DMK81E #slack #slackapi #thread
Amber Srivastava
Nov 7, 2024
When working with Stimulus, it's common to dynamically update DOM elements. While string interpolation works, using HTML
#CU6U0R822 #stimulus #templates
String interpolation
HTML Templates
<template> elements is a cleaner and more maintainable approach.#CU6U0R822 #stimulus #templates
String interpolation
// In your stimulus controller
updateList() {
this.listTarget.innerHTML = `
<div class="flex gap-2">
<span>${this.name}</span>
<button>Delete</button>
</div>
`
}HTML Templates
// 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)
}Satya
Nov 7, 2024
In a Rails application, we can provide different views and behaviours based on the type of device accessing our application. One of the ways to achieve this is by using the
1. First, determine if the request is coming from a mobile device and set variant in the controller.
2. Now, create mobile-specific views. For example, if we have an
With the variant set, Rails will automatically choose the correct view.
#rubyonrails
set_variant method along with mobile-specific templates like index.html+mobile1. First, determine if the request is coming from a mobile device and set variant in the controller.
def set_variant
browser = Browser.new(request.user_agent)
if browser.device.mobile?
request.variant = :mobile
else
request.variant = :desktop
end
end 2. Now, create mobile-specific views. For example, if we have an
index.html.erb view, we can create a mobile-specific version by adding +mobile to the filename.
app/views/orders/index.html.erb
app/views/orders/index.html+mobile.erbWith the variant set, Rails will automatically choose the correct view.
#rubyonrails
Syed Sibtain
System Analyst
Nov 6, 2024
useFetch 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.Key Difference:
•
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.#fetch #nuxt #useFetch #useAsyncData
Ayasha Pandey
System Analyst
Nov 4, 2024
In Rails, forms can be created in two ways: with a URL (using
But, when to use which?
Form with URL (
This form is used when you specify a URL directly and typically use it for non-resourceful actions or when you don’t have a specific model associated with the form.
The
Form with Model (
This form is bound to an instance of a model, allowing Rails to automatically set the form action (URL) and method (POST or PATCH) based on whether the model is a new record or an existing one.
Rails determines the correct URL and HTTP method based on the record's state:
• New Record: If
• Existing Record: If
The
#ruby on rails
form_with url: ...) or with a model (using form_with model: ...).But, when to use which?
Form with URL (
form_with url: ...)This form is used when you specify a URL directly and typically use it for non-resourceful actions or when you don’t have a specific model associated with the form.
<%= form_with url: some_path, method: :post do |form| %>
<%= form.text_field :some_field %>
<%= form.submit "Submit" %>
<% end %>The
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 (
form_with model: ...)This form is bound to an instance of a model, allowing Rails to automatically set the form action (URL) and method (POST or PATCH) based on whether the model is a new record or an existing one.
<%= form_with model: @record do |form| %>
<%= form.text_field :name %>
<%= form.submit %>
<% end %>Rails determines the correct URL and HTTP method based on the record's state:
• New Record: If
@record.new_record? is true, Rails generates a POST request to the model’s create route.• Existing Record: If
@record.persisted? is true, Rails generates a PATCH request to update the model’s update route.The
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.).#ruby on rails
Nitturu Baba
System Analyst
Nov 4, 2024
To update a user’s password in
#auth #aws #cognito
AWS Cognito and set it as permanent, we can use the AWS CLI with the following admin command:
aws cognito-idp admin-set-user-password \
--user-pool-id <pool-id> \
--username <cognito-username> \
--password <password> \
--permanent#auth #aws #cognito
Adithya Hebbar
System Analyst
Nov 4, 2024
Query Defaults in React-Query
Any option we pass to React-Query besides the
• Passing
• Setting default options for subset of queries using
• Setting default options within useQuery for fine grain control over specific query.
Each method takes precedence over the others in this order.
#react-query #customizing-defaults
Any option we pass to React-Query besides the
query key can have its default values and can be set by following ways:• Passing
defaultOptions object to query client as global defaults.
const queryClient = new QueryClient(
defaultOptions: {
queries: {
staleTime: 10 * 1000
}
}
}• Setting default options for subset of queries using
Fuzzy Matching by setQueryDefaults method
queryClient.setQueryDefaults(
['todos','list'],
{staleTime: 10 * 1000}
)
//This sets default stale time of 10secs for all the matched queries having keys 'todos' and 'list'• Setting default options within useQuery for fine grain control over specific query.
useQuery({
queryKey: ['todo'],
staleTime: 10 * 1000,
});Each method takes precedence over the others in this order.
#react-query #customizing-defaults
Anujeet Swain
System Analyst
Nov 4, 2024
Promise.allSettled() :
Purpose: Executes multiple promises and waits for all of them to settle (either resolve or reject).
Returns: A promise that resolves with an array of objects. Each object has:
•
•
Example
#CCT1JMA0Z
Purpose: Executes multiple promises and waits for all of them to settle (either resolve or reject).
Returns: A promise that resolves with an array of objects. Each object has:
•
status: Either "fulfilled" or "rejected".•
value: The resolved value (if fulfilled) or reason: The rejection reason (if rejected).Example
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: 2#CCT1JMA0Z
Amber Srivastava
Oct 30, 2024
Git Rebase:
It is similar to merge, but the difference is merging brings the changes from the
Rebasing applies your branch’s commits on top of the
• First pull the latest changes of main branch.
• Then navigate to the working branch
• run the command git rebase main
• if there any conflicts resolve and continue rebase.
• After rebasing completely, force push the changes.
#git
It is similar to merge, but the difference is merging brings the changes from the
main branch into your current branch by creating a merge commit that combines the histories of both branches.Rebasing applies your branch’s commits on top of the
main branch, making it look as if your work was started from the latest main commit.• First pull the latest changes of main branch.
• Then navigate to the working branch
• run the command git rebase main
• if there any conflicts resolve and continue rebase.
• After rebasing completely, force push the changes.
#git
Nitturu Baba
System Analyst
Oct 29, 2024
To avoid N+1 queries in Rails, you can use the
Suppose you have two models:
By using
This approach loads
#CU6U0R822
.includes method to eager-load associated records, which reduces the number of database calls.Suppose you have two models:
Order and Item, where an Order has many Items. Without eager-loading, querying each order’s items individually would lead to N+1 queries.
orders = Order.all
orders.each do |order|
puts order.items # Each order triggers a separate query for items
endBy using
.includes, Rails will fetch all associated items in a single additional query:
orders = Order.includes(:items)
orders.each do |order|
puts order.items # No extra query is triggered here
endThis approach loads
Order records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.#CU6U0R822
Nitturu Baba
System Analyst
Showing 12 to 14 of 82 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