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
Nived Hari
System Analyst
Concerns
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern module provided by Rails.
They help in organizing and reusing code across controllers and models by extracting common functionality into modules.


There are 2 main blocks in a concern

1. included

1. Any code inside this block is evaluated in the context of the including class.
2. if sample class includes a concern, anything inside the included block will be evaluated as if it was written inside the sample class.
3. This block can be used to define Rails macros like validations, associations, and scopes.
4. Any method you create here becomes instance methods of the including class.
2. class_methods

1. Any methods that you add here become class methods on the including class.
Example:

typically concerns are located in app/controllers/concerns or app/models/concerns

Code

module ExampleConcern
  extend ActiveSupport::Concern

  included do
    # any code that you want inside the class
    # that includes this concern
  end

  class_methods do
    # methods that you want to create as
    # class methods on the including class
  end
end


Including this concern in a controller:


Code

class SomeController < ApplicationController
 include ExampleConcern
end


#RubyOnRails #concerns #CU6U0R822
Published
Author
user-image
Adithya Hebbar
System Analyst
Here is how to generate robots.txt in Next.Js - App Router. Add a robots.js or robots.ts file in your app directory

Code

import type { MetadataRoute } from 'next'
 
export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
      disallow: '/private/',
    },
  }
}


This will add or generate a robots.txt file that matches the https://en.wikipedia.org/wiki/Robots.txt#Standard|Robots Exclusion Standard in the root of app directory to tell search engine crawlers which URLs they can access on your site.

#js #nextjs #seo
Published
Author
user-image
Ayush Srivastava
System Analyst
We can generate a UUID in Rails using SecureRandom.uuid without needing any gem
#CU6U0R822
Published
Author
user-image
Giritharan
System Analyst
Managing Global Attributes with ActiveSupport::CurrentAttributes in Rails

In Rails, ActiveSupport::CurrentAttributes simplifies the process of storing global, thread-safe data like Current.user or Current.account during requests or jobs. It should be limited to top-level globals, such as user and request details, which are needed across all actions.

In controllers, Rails automatically resets Current between requests, so we don’t need to manually clear it. However, In Active Jobs, we need to manually reset Current after each job to prevent data from leaking between job executions. We achieve this using the after_perform callback.

Code Example:
*app/models/current.rb*:


Code

class Current < ActiveSupport::CurrentAttributes
  attribute :user, :account, :request_id
end


app/jobs/my_job.rb:


Code

class MyJob < ApplicationJob
  after_perform :clear_current_attributes

  def perform(params)
    set_current_attributes(params[:user_id])
  end

  private

  def set_current_attributes(user_id)
    Current.user = User.find_by(id: user_id)
    Current.request_id = SecureRandom.uuid
  end

  def clear_current_attributes
    Current.reset
  end
end


In summary: Rails handles resetting Current for controllers, but for jobs, we must manually reset it after each job to avoid data leakage.

#current #currentAttributes #CU6U0R822
Published
Author
user-image
Aman Suhag
System Analyst
In TypeScript, a tuple is a typed array with a fixed number of elements, where each element may have a different type. Unlike regular arrays, which can hold any number of elements of the same type, tuples define a specific sequence of element types and their corresponding positions.
Key Characteristics of Tuples:
1. Fixed Length: The number of elements in a tuple is fixed. You must specify how many elements the tuple can contain.
2. Different Types: Each element in a tuple can be of a different type. The type for each position is defined.
3. Access by Index: Elements are accessed by their index, just like regular arrays, but the types of the elements at each index are known and enforced by the type system.
let user: [string, number?] = ["Alice"]; // number is optional
#typescript #tuple
Published
Author
user-image
Ayasha Pandey
System Analyst
the fallbackData parameter in useSWR to provide default data for your fetch request. This is super useful when you want to display initial data while waiting for the network request to resolve. The fallback data will be used as the initial value for the data until the fetcher returns the actual data.


Code

const {
  data,
  mutate,
  error,
} = useSWR(endpoint, fetcherFunction, {
  fallbackData: initialData,
});


#swr #hook
Published
Author
user-image
Soniya Rayabagi
"Adding a User to the Docker Group on Ubuntu"
1. sudo groupadd docker # Create the Docker group if it doesn't exist
2. sudo usermod -aG docker $USER # Adds the current user to the 'docker' group.
3. newgrp docker # Apply the new group membership
4. docker run hello-world # Checks if the user can run Docker commands without sudo
#Ubuntu #DevOps #Docker
Published
Author
user-image
Amber Srivastava
useFormContext hook

The useFormContext hook is a part of react-hook-form and allows you to access form methods (such as setValue, getValues, etc.) from any component nested inside the FormProvider. This is useful when you want to manage the form state across deeply nested components without passing props down manually.

Steps to Use useFormContext:
1. Wrap your form with FormProvider: This allows any child component to access the form context via useFormContext.
2. Access form methods using useFormContext: In your component, you can call useFormContext to access setValue, getValues, etc.
Example
1. In your main form component: Wrap your form with FormProvider and pass in useForm's returned values.

Code

import { useForm, FormProvider } from "react-hook-form";

const FormComponent = () => {
  const methods = useForm();

  return (
    
      
        {/* Now any nested component can use useFormContext */}
        
        {/* Submit button or other components */}
      
    
  );
};


2. In your ChildComponent or any other component: Use useFormContext to access the form methods like setValue or getValues.

Code

import { useFormContext } from "react-hook-form";

const ChildComponent = () => {
  const { setValue } = useFormContext(); // useFormContext gives access to all form methods

  return (
    
      {/* Dropdown logic */}
    
  );
};


#useForm #CCT1JMA0Z
Published
Author
user-image
Giritharan
System Analyst
Managing Jobs in SolidQueue with Rails Console

SolidQueue::RecurringExecution.all : You can find and manage recurring jobs with this query.
SolidQueue::ReadyExecution.all: Use this query to identify jobs that are ready to run but haven’t started yet.
SolidQueue::BlockedExecution.all: Find jobs that are blocked and waiting for conditions to be met before execution.
SolidQueue::ClaimedExecution.all: Check jobs that have been claimed by workers but are still in progress.
SolidQueue::FailedExecution.all: Use this to track jobs that failed during execution.
SolidQueue::ScheduledExecution.all: Find jobs that are scheduled for future execution.
SolidQueue::Job.where(finished_at: nil): Query to get jobs that are still running or haven’t finished yet.
#activejob #solidqueue #queriesforsolidqueue #CU6U0R822
Published
Author
user-image
Adithya Hebbar
System Analyst
Here’s how to update the most recent commit with new changes:

git commit --amend --no-edit command allows you to modify the most recent commit without changing its commit message.

• The --amend flag updates the previous commit with the new changes.
• The --no-edit option keeps the existing commit message unchanged.
After amending the commit, if it has already been pushed to the remote repository, you’ll need to force push the changes using: git push -f

#git #git-commit

Showing 14 to 16 of 83 results

Ready to Build Something Amazing?

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