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
Vaibhav Yadav
Senior System Analyst
Using Makefile for tedious commands

A Makefile can be used to automate a commands, simplifying the execution process. Here’s a concise example:


Code

.PHONY: run-script

# Target to run a long command
run-script:
    @echo "Running a long command..."
    sleep 5  # Simulate a long-running command
    @echo "Command completed."


Running the Makefile
1. Create a Makefile: Save the above content as Makefile in your project directory.
2. Run Make: In your terminal, navigate to the project directory and execute:

Code

make run-script


Benefits
β€’ Simplicity: Easily run a long command without remembering the syntax.
β€’ Automation: Reduces manual effort and potential errors.
#cli #automation #makefile #commands
Published
Author
user-image
Sudeep Hipparge
πŸ’‘ Why is [] == ![] true in JavaScript?

It all comes down to type coercion and how JavaScript evaluates expressions using the == (abstract equality) operator.

Here’s the breakdown:
![] evaluates to false because an empty array is truthy, and the ! operator negates it.
So the expression becomes: [] == false
When comparing an object (like[]) to a boolean with==, JavaScript converts both sides to numbers:
+[] β†’ 0
+false β†’ 0
So:

Code

[] == ![]  
=> [] == false  
=> +[] == +false  
=> 0 == 0  
=> true


βœ… Hence, [] == ![] evaluates to true.

#CCT1JMA0Z
Published
Author
user-image
Adithya Hebbar
System Analyst
How Dependency Injection Works in NestJS

NestJS uses Dependency Injection (DI) to manage the creation and lifecycle of classes like services, repositories, and providers. It leverages TypeScript's metadata to resolve dependencies automatically.

πŸš€ How It Works:

β€’ Declare Providers: Services and other classes are marked with @Injectable() to make them available for dependency injection. They are then registered as providers in a module.

Code

// user.service.ts
@Injectable()
export class UserService {
  getUsers() {
    return ['Alice', 'Bob'];
  }
}


β€’ Register Providers in a Module

Code

// user.module.ts
@Module({
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}


β€’ Use the Service via Constructor Injection

Code

// user.controller.ts
@Controller('users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  findAll() {
    return this.userService.getUsers();
  }
}


NestJS reads the constructor types and injects the required instances for you. No manual instantiation needed!

βœ… Benefits:
β€’ Decouples components
β€’ Simplifies testing with mocks
β€’ Promotes cleaner, modular code

#nestjs #dependencyinjection #typescript
Published
Author
user-image
Sudeep Hipparge
How to Revoke and Amend the Most Recent Git Commit Message.
To undo the most recent commit, unstage the changes, and update the commit message, follow these steps:

1. Revoke the latest commit and unstage the changes.
git reset HEAD~1

2. Stage the changes again.
git add .

3. Create a new commit with the updated message
git commit -m "New commit message"
(If you just want to change the previous commit message) - git commit --amend

4. Force-push the new commit to the remote repository
git push origin <branch-name> --force

> ⚠️ Use --force cautiously, especially on shared branches, as it rewrites history.
Published
Author
user-image
Nived Hari
System Analyst
pgvector provides native support for vector similarity search in PostgreSQL. It supports three types of distance metrics, each useful depending on the use case:
β€’ <=> Cosine distance – Measures the angle between two vectors (ignores magnitude). Great for comparing meaning in text (e.g., NLP). Smaller angle = more similar.
β€’ <#> L2 (Euclidean distance) – Measures the straight-line distance between two vectors. Takes both direction and size into account. Good when actual value differences matter (like in image or audio data).
β€’ <-> Inner product – Measures how much two vectors point in the same direction and how large they are. If vectors are normalized (length = 1), it works like cosine similarity. Great for ranking similarity when vectors are preprocessed.

#pgvector #PostgreSQL #VectorSearch #Embeddings
Published
Author
user-image
Puneeth kumar
System Analyst
ClickHouse DB

It is a column-oriented database management system designed for online analytical processing (OLAP). It's optimised for real-time analytics on large volumes of data and is known for being fast, highly scalable, and efficient for read-heavy workloads like metrics, logs, events, and other analytical data.

Key features are -
1. Columnar storage : Stores data by columns instead of rows, enabling efficient compression and faster reads.
2. Works super fast : Designed to process billions of rows per second per server.
3. SQL-compatible.
4. Materialized views : For real-time aggregation and data transformation.
#databases #click_house_db #analytics
Published
Author
user-image
Puneeth kumar
System Analyst
Validating date and time field in Rails

validates_timeliness gem helps us to check if a date or time field is valid and meets certain conditions β€” like being in the past, in the future, or within a specific range. It can do following things.
1. Check if a date is valid (e.g., "2025-02-30" is not a valid date).
2. Make sure a date is before or after a certain time as needed.
3. Restrict a field to only accept dates, times or datetimes.
4. Works well with user input in different formats.
For example :

Code

class Event < ApplicationRecord
  validates_timeliness :start_time, on_or_after: :now, type: :datetime
end


This makes sure start_time is not in the past.

#CU6U0R822 #date_time_validation
Published
Author
user-image
Mohammad hussain
System Analyst
friendly_id is a Rails gem that lets you use secure, human-readable slugs instead of record IDs in URLs.
https://github.com/norman/friendly_id
it updates the url
from this :

Code

https://localhost:3000/employer/job_posts/2/job_applications/new


to this:

Code

https://localhost:3000/employer/job_posts/frontend-developer-37b70ea4-761e-4369-832e-f5b373f7f00b/job_applications/new


#CU6U0R822
Published
Author
user-image
Syed Sibtain
System Analyst
rails_representation_url in Rails is used to generate a URL for a variant of an Active Storage image, not the original blob. It's especially useful when we want to apply transformations like resizing or converting image formats on-the-fly.


Code

rails_representation_url(
  image.variant(resize_to_limit: [300, 300], saver: { quality: 80 }, format: :webp).processed,
  only_path: true
)


β€’ image.variant(...) creates a variant of the image, resizing it to a maximum of 300x300 pixels, converting it to WebP format, and reducing its quality for optimization.
β€’ .processed ensures the variant is actually processed before generating the URL.
β€’ rails_representation_url(...) then generates the URL for this transformed version.
β€’ only_path: true returns a relative path (instead of a full URL), which is often preferred in views or frontend routing.
This is a great way to deliver performance-optimized images for the UI

#rubyonrails
Published
Author
user-image
Aditya Vishwakarma
System Analyst
Rails provides a https://api.rubyonrails.org/classes/ActiveRecord/TokenFor.html#method-i-generate_token_for|generates_token_for method on Active Record models, which can generate unique tokens for records β€” including support for expiration. This is useful for scenarios like creating unique unsubscribe links in emails. You can later retrieve a record using the generated token with the corresponding https://api.rubyonrails.org/classes/ActiveRecord/TokenFor/RelationMethods.html#method-i-find_by_token_for|find_by_token_for method.

The Rails Authentication generator utilizes this feature in its password reset flow. It uses https://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password|has_secure_password, which by default enables password reset functionality for the user model. When you call the password_reset_token instance method on a user, it internally uses generates_token_for to generate a unique token. You can then find the user record later using find_by_password_reset_token.

By default, https://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html#method-i-has_secure_password|has_secure_password uses the password attribute, but you can customize this by specifying a different attribute via the attribute option. If you want to disable password reset functionality, you can pass reset_token: false to has_secure_password (it is enabled by default). Similarly, you can disable password confirmation validations by passing validations: false (validations are enabled by default).

#rubyonrails #ror #authentication #token #password

Showing 5 to 7 of 82 results

Ready to Build Something Amazing?

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