author avatar

nitturu.baba

Tue Oct 08 2024

How to Create a Multi-Language Website in Rails

Ruby on Rails comes with an integrated internationalization (I18n) framework that makes it simple to add multi-language support to your website.

Create Locale Files

You can define your translations using .yml files located in the config/locales directory.
For example, if your website supports English and Hindi, you would create two files: en.yml and hi.yml.

en.yml file:


en:
    hello: "Hello"
    good_morning: "Good Morning %{name}"  # %{name} is used to pass dynamic parameters.
    rails: "Rails"


hi.yml file:


hi:
    hello: "नमस्ते"
    good_morning: "शुभ प्रभात  %{name}"
    rails: "रेल"


Use Translations in Your Views

You can use the t helper method to access translations in your views.



<%= t("hello") %>
// normal usage
<%= t("good_morning", name: t("rails")) %>
// Passing Dynamic Parameters.


Language Switching via URL

The language displayed will depend on the locale set in the URL. For example:
• If the URL is , the English translation will be used.
• If the URL is , the Hindi translation will be used.
#CU6U0R822 #multi-language
author avatar

syedsibtain

Mon Oct 07 2024

A Dead Letter Queue is a special queue in message queue systems that holds messages (payload) that cannot be delivered to their intended recipients due to various reasons.
These reasons can include:

• Incorrect message formatting
• Network errors
• System failures
• Application-level errors
DLQs serve several important purpose.

1. Message Preservation: They prevent loss of messages/payload that fail processing, allowing for later analysis or retry.
2. System Stability: By isolating problematic messages/payload, DLQs prevent failures from affecting the main message flow.
3. Debugging: DLQs provide a centralised location for developers to inspect and diagnose issues with failed messages.
#deadletterqueue #queuemanagement
author avatar

adithya.hebbar

Mon Oct 07 2024

Fly.io release_command

In Fly.io, the release_command is a special one-time command executed before deploying an app. It’s often used for tasks like running database migrations or other setup steps that need to happen before the app is fully launched. You can define it in your fly.toml file under the [deploy] section.

Example:


[deploy]
  release_command = "python manage.py migrate"


This ensures your migrations or other essential pre-deploy tasks run seamlessly during the deployment process!

#fly #db_migrations
author avatar

ayasha.pandey

Mon Oct 07 2024

useFieldArray is a hook provided by React Hook Form that simplifies the process of managing dynamic form fields. It allows you to create forms where users can add, remove, move, and manipulate groups of inputs (or arrays of fields), like a list of tasks, addresses, or any repeatable form sections.
Features :-
1. Dynamic Fields Management
2. Efficient Rendering
Functions Provided by useFieldArray
append(): Adds a new item to the end of the field array.
prepend(): Adds a new item to the beginning of the field array.
remove(index): Removes a field at the specified index.
insert(index, value): Inserts a new field at a specific index.
#react-hook #react-form #form
author avatar

amber.srivastava

Mon Oct 07 2024

To create a model in Prisma:
1. Open the schema.prisma file.
2. Define datasource and generator:


datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}


Create the model:


model Retro {
  id              String   @id @default(cuid())
  date            DateTime @default(now())   // Auto-fills current date
  scrumMasterId   String                        // For Scrum Master (User)
  slackChannel    String                        // Slack Channel input
  questions       String[]                      // Default retro questions
  projectId       Int       @relation(fields: [projectId], references: [id])
  project         Project   @relation(fields: [projectId], references: [id])
}


This creates the Retro table for your retrospectives.

@id: Marks a field as the primary key.
@default(): Sets a default value for a field.
@relation(): Defines relationships between models.
@unique: Ensures a field has unique values.
String[]: Defines an array of strings.
cuid(): Generates a unique ID.
@updatedAt: Automatically updates the field with the current timestamp when data changes.

#prisma #database #columns #model
author avatar

aman.suhag

Mon Oct 07 2024

Mocking in Jest
Jest provides several ways to mock:
jest.fn(): Creates a mock function that you can use instead of a real function.
jest.mock(): Mocks entire modules.
jest.spyOn(): Tracks calls to an existing method while optionally replacing its implementation.
#jest #test #mock
author avatar

ashwanikumarjha

Wed Oct 02 2024

Async Local Storage in Node.js

• Provides us a way to store and manage context-specific data across asynchronous operations without needing to pass it explicitly through function arguments.
• Built on the async_hooks module, which tracks asynchronous resource lifecycle events.
• We need to use asyncLocalStorage.run(store, callback) to create a new context.
• Asynchronous operations initiated within this callback inherit that context.
• Each context created with asyncLocalStorage.run() is unique and does not interfere with other contexts.
• Common use cases can be maintaining custom context in our web app (e.g., request data, user ID...) across multiple layers (controllers, services, etc.), can help us with tracing how a request propagates through different async functions.
• Automatically cleans up the context after the asynchronous operations are complete.
run(store, callback): Creates a new context and runs the callback with the provided store (like a Map or a primitive value).
• Set a value: asyncLocalStorage.getStore().set('requestId', requestId);
• Get a value: const requestId = asyncLocalStorage.getStore().get('requestId');


const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');
const { v4: uuid } = require('uuid');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const requestId = asyncLocalStorage.getStore(); 
  console.log(`${requestId} - ${msg}`);
}

function serviceA() {
  logWithId('Service A log');
}

function serviceB() {
  logWithId('Service B log');
}

http.createServer((req, res) => {
  const requestId = uuid();
  asyncLocalStorage.run(requestId, () => { 
    logWithId('Request received');
    serviceA();
    serviceB();
    logWithId('All services called');
    res.end('Response sent');
  });
}).listen(4040);

http.get('');

// Output:
<generated-request-id> - Request received
<generated-request-id> - Service A log
<generated-request-id> - Service B log
<generated-request-id> - All services called

author avatar

vaibhav.yadav

Mon Sep 30 2024

## Avoid Mutating Objects Loaded from JSON Files

Today I learned that even if data is loaded from a static JSON file - once it's parsed and stored as a JavaScript object in memory, it behaves like any other object—meaning it's mutable by reference.

This means that modifying a property of an object loaded from a JSON file will mutate the original object in memory, affecting all references to that object across the app.

To avoid accidental mutations, it's best to create a copy of the object (using methods like { ...obj } for shallow copies) before modifying it. This ensures that the original data remains unchanged and helps prevent unexpected side effects throughout the codebase.

Example of creating a copy to avoid mutation:



const content = { ...emails['Signup success'] };


This protects the original emails object from being modified, keeping the rest of the app safe from unintended changes.

---

It's a small but important detail when dealing with mutable JavaScript objects loaded from static sources!

#passByReference #js #json #objects
author avatar

nitturu.baba

Mon Sep 30 2024

The default behavior of a form's submit button in Rails is to disable itself once the form has been submitted. In any situation if you want to submit form multiple times without reloading the page, we can use a simple trick:

1. Move the submit button outside of the form.
2. Create a controller that connects the button and the form.
3. Implement an action in controller to submit the form when the button is clicked.
Form:


<%= form_with(model: @object, data: {
    controller: "form",
    form_target: "form"
}) do |form| %>
  <%= form.label :name %>
  <%= form.text_field :name %>

  <%= form.label :status %>
  <%= form.select :status, ["Active", "Inactive"] %>

<% end %>

<%= button_tag "submit", type: "submit", data: {
      action: "click->form#formSubmit"
    } %>


Controller:


export default class extends Controller {
    static targets = ["form"];

    formSubmit(){
        this.formTarget.submit()
    }
}


Why This Works
By placing the button outside the form, it becomes unlinked from the form submission process, allowing it to remain enabled even after the form is submitted.

#CU6U0R822 #form #stimulus
author avatar

anujeet.swain

Mon Sep 30 2024

While using React-Query, Cache invalidation is key for keeping your data up-to-date with server state.
Data becomes "stale" after a set time (staleTime), and stale data gets re-fetched when the query is re-triggered (e.g., on component remount, on focus, or on manual refetch).

Following cache invalidation techniques are used to set the data as "stale" in react query:
• Implicitly setting up the staleTime .
• Adding triggers to react-query: refetchOnWindowFocus , refetchOnReconnect, refetchOnMount , refetchInterval .
• Manual invalidation for specific queries using queryClient.invalidateQueries() .
To have more control over specific query invalidation, we can utilise the queryKey property:


queryClient.invalidateQueries({
  queryKey: ['todos'],
})




queryClient.invalidateQueries({
  queryKey: ['todos', { type: 'done' }],
})


#react-query #cache-invalidation #data-synchronization

Showing 5 to 7 of 72 results