Skip to content

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.

  1. Using Ruby's built-in URI::MailTo::EMAIL_REGEXP for email validation is generally better than using a custom regular expression due to its robustness, reliability, and maintenance by the Ruby core team.

    Ruby

    class User < ApplicationRecord
      has_secure_password
      validates :name, presence: true
    
      # Using a custom regular expression for email validation
      validates :email, presence: true, format: { with: /\\A[^@\\s]+@[^@\\s]+\\z/ }, uniqueness: true
      
      # Using Ruby's built-in URI::MailTo::EMAIL_REGEXP for email validation
      validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }, uniqueness: true
    
    end


    #ruby #regex #rails
  2. Fixing Image Rendering in Rails with Active Storage
    How to fix the error PG::UndefinedTable: ERROR: relation "active_storage_attachments" does not exist

    This error occurs because Active Storage in Rails relies on specific database tables (e.g., active_storage_attachments and active_storage_blobs) to store metadata about attached files. If these tables do not exist, Rails cannot store or retrieve the necessary metadata for file attachments, resulting in the mentioned error.

    By following these steps, we ensure that the necessary Active Storage tables are created, allowing Rails to store and retrieve image metadata correctly.

    Run Active Storage Installation:

    Ruby

    rails active_storage:install


    Migrate the Database:

    Ruby

    rails db:migrate


    Restart the Rails Server:

    Ruby

    rails server


    Then in views we can simply use the helper and render the image

    Ruby

    <%= image_tag url_for(recipe.image), class: "w-full h-64 object-cover" %>


    #rails #activestorage
  3. Soniya Rayabagi
    Terraform Import :
    terraform import allows you to bring existing resources into Terraform's state management without recreating them.
    Syntax: terraform import <RESOURCE_TYPE>.<RESOURCE_NAME> <RESOURCE_ID>
    Example: terraform import aws_s3_bucket.bucket my-existing-bucket

    #devops #TerraformImport
  4. Adithya HebbarSystem Analyst
    To create a dump of all the inserts with data and column names using pg_dump

    Code

    pg_dump -U your_username -d your_database -h your_host -p your_port --column-inserts --data-only -f output.sql


    #postgres #database
  5. To set the autoincrement number in PostgreSQL, use the following query:

    Code

    ALTER SEQUENCE "users_id_seq" RESTART WITH 1000;


    #database #postgresql
  6. Soniya Rayabagi
    Automating Terraform with GitHub Actions:
    I learned how to automate Terraform linting, planning, and applying using GitHub Actions. This helps ensure code is always in good shape and deployed correctly. Here’s a step-by-step guide to set it up:
    Steps:
    • Create a .github/workflows/terraform.yml file in your repository. This single file defines the entire workflow for GitHub Actions.
    • Set up the workflow to trigger on pull requests and pushes to the main branch. This ensures that the Terraform configuration is checked and applied automatically whenever changes are made.

    Code

    name: Terraform CI/CD
    
    on:
      push:
        branches:
          - main
      pull_request:
        branches:
          - main
    
    jobs:
      terraform:
        name: Terraform Lint, Plan, and Apply
        runs-on: ubuntu-latest
    
        steps:
        - name: Checkout repository
          uses: actions/checkout@v2
    
        - name: Set up Terraform
          uses: hashicorp/setup-terraform@v2
          with:
            terraform_version: 1.8.3
    
        - name: Terraform Init
          run: terraform init
    
        - name: Terraform Format
          run: terraform fmt -check
    
        - name: Terraform Validate
          run: terraform validate
    
        - name: Terraform Plan
          run: terraform plan
    
        - name: Terraform Apply
          run: terraform apply -auto-approve
          env:
            TF_VAR_user: ${{ secrets.TF_VAR_USER }}


    • Single Workflow File : By using a single .github/workflows/terraform.yml file, I streamline the CI/CD process, making it easier to manage and maintain.
    • Checkout Repository : The actions/checkout@v2 step checks out the repository so that the workflow has access to the Terraform configuration files.
    • Set up Terraform : The hashicorp/setup-terraform@v2 action sets up the specified version of Terraform on the runner.
    • Terraform Init: The terraform init command initializes the working directory containing Terraform configuration files.
    • Terraform Format : The terraform fmt -check command ensures that the Terraform configuration files are properly formatted. This helps maintain a consistent coding style.
    • Terraform Validate : The terraform validate command checks the syntax and configuration of the Terraform files to ensure they are valid.
    • Terraform Plan : The terraform plan command creates an execution plan, showing what actions Terraform will take to reach the desired state. This step allows you to review changes before they are applied.
    • Terraform Apply : The terraform apply -auto-approve command applies the changes required to reach the desired state of the configuration.
    #devops #Terraform #GitHubActions #HashiCorp
  7. Vaibhav YadavSenior System Analyst
    When implementing password and confirmPassword field with react-hook-form and zod for validation, you might need to figure out a way to run the validation for both the fields simultaneously. With the default approach, or the simple implementation you would notice that upon updating password field, the validation for confirm password won't kick in and vice versa.

    One solution for these would be to use Controller from react-hook-form and use superRefine to run your validation simultaneously.

    Snippet:

    Code

    // validation Schema
    import { z } from 'zod';
    
    // Define the schema
    const schema = z.object({
      password: z.string().min(8, 'Password should be at least 8 characters long'),
      confirmPassword: z.string().min(8, 'Password should be at least 8 characters long'),
    }).superRefine((data, ctx) => {
      if (data.password !== data.confirmPassword) {
        ctx.addIssue({
          code: 'custom',
          path: ['confirmPassword'],
          message: 'Passwords do not match',
        });
      }
    });
    
    export default schema;



    Code

    // form component
    import React from 'react';
    import { useForm, Controller } from 'react-hook-form';
    import { zodResolver } from '@hookform/resolvers/zod';
    import schema from './schema'; // Import the schema
    
    const PasswordForm = () => {
      const { handleSubmit, control, formState: { errors } } = useForm({
        resolver: zodResolver(schema),
      });
    
      const onSubmit = (data) => {
        console.log('Form Data:', data);
      };
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <div>
            <label>Password</label>
            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <input
                  type="password"
                  {...field}
                  placeholder="Enter your password"
                />
              )}
            />
            {errors.password && <span>{errors.password.message}</span>}
          </div>
    
          <div>
            <label>Confirm Password</label>
            <Controller
              name="confirmPassword"
              control={control}
              render={({ field }) => (
                <input
                  type="password"
                  {...field}
                  placeholder="Confirm your password"
                />
              )}
            />
            {errors.confirmPassword && <span>{errors.confirmPassword.message}</span>}
          </div>
    
          <button type="submit">Submit</button>
        </form>
      );
    };
    
    export default PasswordForm;


    Second solution, just in case if you're not using the react-hook-form's Controller would be using the trigger and touchedFields from react-hook-form and using react's classic useEffect:


    Code

    // component with Schema
    import React, { useEffect } from 'react';
    import { useForm } from 'react-hook-form';
    import { zodResolver } from '@hookform/resolvers/zod';
    import { z } from 'zod';
    
    const schema = z.object({
      password: z.string().min(8, 'Password should be at least 8 characters long'),
      confirmPassword: z.string().min(8, 'Password should be at least 8 characters long'),
    }).superRefine((data, ctx) => {
      if (data.password !== data.confirmPassword) {
        ctx.addIssue({
          code: 'custom',
          path: ['confirmPassword'],
          message: 'Passwords do not match',
        });
      }
    });
    
    const PasswordForm = () => {
      const { handleSubmit, register, trigger, formState: { errors, touchedFields } } = useForm({
        resolver: zodResolver(schema),
      });
    
      const onSubmit = (data) => {
        console.log('Form Data:', data);
      };
    
      useEffect(() => {
        if (touchedFields.password) {
          trigger('password');
        }
      }, [trigger, touchedFields.password]);
    
      useEffect(() => {
        if (touchedFields.confirmPassword) {
          trigger('confirmPassword');
        }
      }, [trigger, touchedFields.confirmPassword]);
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <div>
            <label>Password</label>
            <input
              type="password"
              {...register('password')}
              placeholder="Enter your password"
            />
            {errors.password && <span>{errors.password.message}</span>}
          </div>
    
          <div>
            <label>Confirm Password</label>
            <input
              type="password"
              {...register('confirmPassword')}
              placeholder="Confirm your password"
            />
            {errors.confirmPassword && <span>{errors.confirmPassword.message}</span>}
          </div>
    
          <button type="submit">Submit</button>
        </form>
      );
    };
    
    export default PasswordForm;


    Happy Coding!!! 🙂

    #reactHookForm #react #formValidation #zod #useEffect
  8. Soniya Rayabagi
    To connect to the PostgreSQL RDS instance using psql:

    Code

    psql -h ${postgres_host} -U "${postgres_username}" -d ${postgres_database} -W


    where, ${postgres_host}: variable representing the PostgreSQL host or db endpoint

    #devops #PostgreSQLConnection #rds
  9. Soniya Rayabagi
    Install powerful monitoring tools, Grafana and Prometheus
    Grafana:
    • Install with Homebrew: brew install grafana
    • Start the service: brew services start grafana
    • Access at https://localhost:3000 (default login: admin/admin)
    • Stop the service: brew services stop grafana
    Prometheus:
    • Install with Homebrew: brew install prometheus
    • Configure prometheus.yml:

    Code

    global:
      scrape_interval: 10s
    
    scrape_configs:
      - job_name: 'prometheus'
        static_configs:
          - targets: ['localhost:9090']


    where -> scrape_interval: 10s: Prometheus will collect metrics from all defined targets every 10 seconds.
    scrape_configs: This section defines how Prometheus should scrape metrics from targets.
    • Start with configuration: prometheus --config.file=prometheus.yml
    • Access at https://localhost:9090
    #devops #grafana #prometheus
  10. GiritharanSystem Analyst
    overscroll-behavior in CSS

    The overscroll-behavior CSS property controls what happens when you reach the boundary of a scrollable area. It's useful for managing scroll chaining and preventing unwanted browser behaviors like the "bounce" effect or "pull to refresh."

    Usage
    - Default (auto): Normal scroll behavior.
    - Contain: Stops scroll chaining; keeps default behavior within the element.
    - None: Prevents both scroll chaining and the default overflow behavior.

    Examples
    Prevent underlying content from scrolling:

    .scroll-container {
    height: 220px;
    overflow: auto;
    overscroll-behavior-y: contain;
    }

    Disable overscroll effects:

    html {
    margin: 0;
    overscroll-behavior: none;
    }

    #css #alignment-issue #frontend
  11. Ashwani Kumar JhaSenior System Analyst
    Beacon API

    Reliable way to send asynchronous data to a server, especially during page unload events. The Beacon API lets us send small amounts of data asynchronously and non-blockingly to a server. Unlike traditional solution like fetch, the Beacon API ensures that the data is sent before the page unloads and runs to completion. The browser ensures that the request is initiated before the page is completely unloaded. This includes scenarios where the user closes the tab, navigates to another page, or reloads the page. The primary goal is to deliver the data reliably. The browser ensures that the data transfer completes before the document is discarded.


    JavaScript

    window.addEventListener('beforeunload', () => {
    const data = JSON.stringify({ userId: '12345' });
    navigator.sendBeacon('/logout', data);
    });

  12. Adithya HebbarSystem Analyst
    In JavaScript, console.time is a method that helps you measure the time it takes for a specific block of code to execute. It's like a stopwatch for your code.

    JavaScript

    // Start the timer 
    console.time('myTimer');
    for (let i = 0; i < 1000000; i++) { 
     // Some code here 
    }
    // Stop the timer 
    console.timeEnd('myTimer');


    So, when you run this code, you'll see something like: "myTimer: 1.358ms"

    #javascript
  13. Ashwani Kumar JhaSenior System Analyst
    Performance API

    Seems super useful for tracking web performance, it let us measure various performance metrics of web pages, like how long specific operations take.

    1. performance.now()
    ◦ Provides the current time in milliseconds with high precision, can be useful for measuring how long specific tasks take.
    2. PerformanceEntry
    ◦ Object representing a metric. It includes:
    ▪︎ navigation: Information about page loads.
    ▪︎ resource: Data on loaded resources like scripts and images.
    ▪︎ mark: User-defined timestamps.
    ▪︎ measure: Duration between two marks.
    3. PerformanceNavigationTiming
    ◦ Specific type of PerformanceEntry for page navigation metrics.
    ◦ Tells us if a page load is due to a navigation, reload, or history action.
    ◦ eg properties: domComplete, domContentLoadedEventEnd, type.
    Probable use Cases:
    • Can help us analyze how long different parts of the page load take.
    • Can help us check how long it takes to load each resource.
    • Can help us determine if a page is reloaded or newly navigated.
    #performance #browser
  14. Ashwani Kumar JhaSenior System Analyst
    EJS, the templating engine for JavaScript, allows us to generate HTML markup with plain JavaScript.

    By default, EJS escapes any HTML entities in the output to prevent issues such as cross-site scripting. This is done by replacing characters like <, >, &, and " with their respective HTML entity codes.

    For example:


    JavaScript

    - `&` is replaced with `&`
    - `<` is replaced with `<`
    - `>` is replaced with `>`
    - `"` or `'` (double or single quote) is replaced with `&quot;` or `&#39;` respectively.


    Unescape HTML entities with <%- %>

    If we want EJS to output our data without escaping HTML entities, replace <%= %> with <%- %>. This instructs EJS to render the data as unescaped.
  15. GiritharanSystem Analyst
    My Rails application is named xyz. When I tried to create a scaffold with the same name as the application, it caused a below error.

    Ruby

    The name 'Xyz' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative or use --skip-collision-check or --force to skip this check and run this generator again.


    To fix this, I changed the module name in application.rb to abc. After making this change, everything worked. It's always best to avoid using the same name for both the model and the application.

    #rails-naming-convention #rails
  16. GiritharanSystem Analyst
    After pushing my changes to the Fly, I noticed that my Application JS controller wasn't being found. The problem was due to an incorrect line in app/javascript/controllers/application.js. It originally had:


    JavaScript

    import { application } from "./application";


    To fix it, I changed it to:


    JavaScript

    import { application } from "controllers/application";


    These changes ensured that the request was directed to the correct location, and the Stimulus JS controller started working.


    #stimulus #assert-not-loading #rails
  17. Common procedure to monitor data in Devops Environment

    First we need a source of metrics that can be Applications, Databases, Containers etc

    After that we need Exporters

    Exporters are components that collect and export metrics from various systems, applications, and services, making them available to monitoring tools

    Then we need Datasource

    Datasource aggregates, stores, and allows querying of the metrics collected from Exporters, making it the data source for visualization tools and alerting mechanisms.

    Collected data is stored in Time Series database

    A time series database (TSDB) is a special type of database designed to store and manage data that is recorded over time. Each piece of data has a timestamp, which helps keep track of when it was collected.

    Then comes the visualisation part

    We can use tools like Grafana that make use of the data that is stored in Time Series Database like prometheus to visualise data

    #monitoring #devops
  18. Adithya HebbarSystem Analyst
    util.inspect use-case:

    • Without util.inspect

    JavaScript

    const obj = {
      name: "Adi",
      age: 24,
      details: { details1: { details2: { hobbies: "travelling" } } },
    };
    console.log(obj);
    //Output: { name: 'Alice', age: 30, details: { details1: { details2: [Object] } } }


    • With util.inspect

    JavaScript

    import util from "util";
    
    const obj = {
      name: "Adi",
      age: 24,
      details: { details1: { details2: { hobbies: "travelling" } } },
    };
    
    console.log(util.inspect(obj, { depth: null, colors: true }));
    
    //Output: { name: 'Adi', age: 24, details: { details1: { details2: { hobbies: 'travelling' } } } }


    console.log doesn't show all details of complex objects, especially nested ones or hidden properties. util.inspect gives a complete and customizable view for better debugging and understanding.

    #javascript
  19. Adithya HebbarSystem Analyst
    To kill a process running on a specific port in mac:
    1. lsof -i :<port_number>
    2. Note the PID of the process from the output.
    3. kill -9 <pid>
    #killprocess
  20. Password recovery command for Influxdb when running in local as the UI does not provide any other way to set a new password if you have forgotten


    Code

    influxd recovery user update \\
      --username example-username \\
      --password ExAmPL3-paS5W0rD


    #influxdb

Showing page 11 of 42

Your competitors are already using AI. The question is how fast you want to unlock the value.

  • Don't know where to start?

    AI is everywhere but it's unclear which investments will actually move your metrics and which are expensive experiments.

  • Your data isn't ready

    Most AI projects fail at the data layer. Pipelines, quality, access all need work before LLMs can deliver value.

  • Internal teams are stretched

    Your engineers are shipping product. They don't have capacity to also become AI specialists with production-grade experience.

  • Legacy systems block everything

    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.

Book a free discovery call