TILs - 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.

Published
Author
user-image
Syed Sibtain
System Analyst
The dig method in Ruby is used to safely extract nested values from arrays or hashes. It allows us to traverse a data structure without worrying about whether each level of the structure exists, thus avoiding NoMethodError exceptions that occur when trying to call methods on nil.

Syntax:

Code

hash_or_array.dig(*keys)


Example:

Code

data = {
  user: {
    profile: {
      name: "John",
      age: 30
    }
  }
}

name = data.dig(:user, :profile, :name) # => "John"


#ruby #CU6U0R822
Published
Author
user-image
Vaibhav Yadav
Senior System Analyst
### PostgreSQL's Foreign Data Wrapper (FDW)

PostgreSQL's Foreign Data Wrapper (FDW) extension and its capabilities for accessing remote databases. FDW provides a standard method for connecting to and querying tables in different databases as if they were part of the local database. This feature is particularly useful for integrating data across multiple PostgreSQL instances or accessing data from different servers.

#### What is FDW?

Foreign Data Wrapper (FDW) is an extension in PostgreSQL designed to connect to external data sources. With FDW, users can perform operations on remote tables seamlessly, making it easier to integrate and analyze data across various systems.

#### How to Use FDW

Here's a concise guide on setting up and using FDW:

1. Install the FDW Extension:
To enable FDW, the extension must be installed in the PostgreSQL database:


Code

sql
   CREATE EXTENSION IF NOT EXISTS postgres_fdw;



2. Create a Foreign Server:
Define the remote database connection details, including the host, port, and database name:


Code

sql
   CREATE SERVER my_foreign_server
   FOREIGN DATA WRAPPER postgres_fdw
   OPTIONS (host 'your_host', port '5432', dbname 'remote_db');



3. Set Up User Mapping:
Configure authentication details for accessing the remote server:


Code

sql
   CREATE USER MAPPING FOR local_user
   SERVER my_foreign_server
   OPTIONS (user 'remote_user', password 'remote_password');



4. Create Foreign Tables:
Define tables in the local database that map to the remote database tables:


Code

sql
   CREATE FOREIGN TABLE foreign_table_name (
       column1 datatype,
       column2 datatype
       -- other columns
   )
   SERVER my_foreign_server
   OPTIONS (schema_name 'public', table_name 'remote_table');



5. Query the Foreign Tables:
Query the foreign tables as if they were local tables:


Code

sql
   SELECT * FROM foreign_table_name;



#### Example Use Case

For instance, if there are two databases on the same PostgreSQL server—sales_db and hr_db—FDW can be used to access employee data from hr_db while working within sales_db. This setup simplifies data integration and reporting across different databases.

FDW streamlines data access and management, providing a powerful tool for integrating and analyzing data from multiple sources within PostgreSQL.

#postgres #database #fdw
Published
Author
user-image
Adithya Hebbar
System Analyst
To make your Django application ASGI-compatible and run it with Daphne, follow these steps:

1. Install Daphne: Install Daphne if you haven't already:


Code

pip install daphne


2. Ensure ASGI Configuration: Your asgi.py file should look like this:


Code

import os
   from django.core.asgi import get_asgi_application

   os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')

   application = get_asgi_application()


3. Update settings.py: Add the ASGI_APPLICATION setting to point to your ASGI application:


Code

ASGI_APPLICATION = 'your_project_name.asgi.application'


Replace 'your_project_name.settings' with the path to your Django settings module.

4. Run Daphne: Start Daphne with your ASGI application using:


Code

daphne -u your_project_name.asgi:application


Alternatively, run it on a specific port:


Code

daphne -p 8000 your_project_name.asgi:application


This setup will get your Django application running with Daphne as the ASGI server.

#python #django #daphne
Published
Author
user-image
Ashwani Kumar Jha
Senior System Analyst
A Lambda layer in AWS Lambda is a feature that lets us manage and share common code and libraries across multiple Lambda functions. By creating a Lambda layer, we can package common code in its own module, which can then be used by our Lambda functions. This reduces duplication and simplifies the management of shared code.
Published
Author
user-image
Adithya Hebbar
System Analyst
We can generate a base64-encoded random key easily using either openssl or a combination of dd and base64. Here's how:


Code

openssl rand -base64 32


Alternatively, using dd and base64:


Code

dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64


Both commands will give you a 32-byte random key encoded in base64.

#encryption #openssl
Published
Author
user-image
Adithya Hebbar
System Analyst
To rename a table in TypeORM, follow these steps:

Create a new migration.

Code

npx typeorm migration:create -n RenameTable


This will create a new migration file in the migrations directory

Edit the Migration File:

Code

import { MigrationInterface, QueryRunner } from "typeorm";

export class RenameTable1724826351040 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.renameTable('old_table_name', 'new_table_name');

    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.renameTable('new_table_name', 'old_table_name');
    }

}


Run the migration:

Code

npm run typeorm -- migration:run


#typeorm #js
Published
Author
user-image
Syed Sibtain
System Analyst
Handling Image Uploads with Active Storage in Rails

Active Storage simplifies file uploads in Rails by attaching files to models.

Setup: Install Active Storage and run rails active_storage:install and rails db:migrate to create necessary tables.

Model Configuration: Use has_many_attached :images to allow multiple image uploads in our model. Example:

Code

class SomeModel < ApplicationRecord
  has_many_attached :images
end


Form: Ensure the form includes multipart: true and allows multiple file uploads with form.file_field :images, multiple: true.

Controller: Permit images in the strong parameters with images: []. Example:

Code

def some_params
  params.require(:some_model).permit(:note, images: [])
end


Migration: Remove old image columns if switching from direct storage to Active Storage.
#CU6U0R822 #activestorage #fileupload
Published
Author
user-image
Adithya Hebbar
System Analyst
To logout from Keycloak using the signOut function in NextAuth, you need to override the default behavior to ensure that the user is properly logged out from Keycloak as well. Here's how you can update your signOut function:

Code

async signOut({ token }) {
  if (token.provider === "keycloak") {
    const issuerUrl = authOptions.providers.find((p) => p.id === "keycloak")
      .options!.issuer!;
    const logOutUrl = new URL(
      `${issuerUrl}/protocol/openid-connect/logout`
    );
    logOutUrl.searchParams.set("id_token_hint", token.id_token!);
    await fetch(logOutUrl);
  }
}


#keycloak #nextauth #nextjs #js
Published
Author
user-image
Giritharan
System Analyst
Delegating Permissions in Pundit:

I encountered a scenario where I needed to retrieve the scope of one policy and use it within another policy. Specifically, I wanted to delegate permissions from one policy to another.

To address this issue, I learned to use Pundit's methods for manually retrieving policies and scopes:
Retrieving a Policy

Code

Pundit.policy(user, record)  # Returns nil if the policy does not exist
Pundit.policy!(user, record) # Raises an exception if the policy does not exist


Retrieving a Policy Scope:

Code

Pundit.policy_scope(user, ModelClass)  # Returns nil if the policy scope does not exist
Pundit.policy_scope!(user, ModelClass) # Raises an exception if the policy scope does not exist


These methods allowed me to delegate permissions effectively by retrieving and applying the appropriate scopes and policies

#rails #pundit #pundit-policy #authorization
Published
Author
user-image
Syed Sibtain
System Analyst
Quick Tip: How can we open a PR from one repository to another repository

1. Create the branch in the current repo

Code

git checkout -b new-branch


2. Add the destination repository as a remote.

Code

git remote add destination https://github.com/username/destination-repo.git


3. Push the new branch to the destination repository

Code

git push destination new-branch


4. To check all the remote repositories added, we can do:

Code

git remote -v


Then, we create a PR in the destination repository from the new branch. This process effectively copies the changes from the original PR into a new PR in a different repository.

#github #git

Showing 17 to 19 of 82 results

Ready to Build Something Amazing?

Codemancers can bring your vision to life and help you achieve your goals