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
Ashwani Kumar Jha
Senior System Analyst
Definite Assignment Checks in TypeScript 5
• Before TypeScript 5:
Code
let value:string;console.log(value); // TS4.x: This was allowed but could lead to runtime undefined
• After TypeScript 5:
Code
let value:string;console.log(value); // TS5.x: Error - Variable 'value' is used before being assigned// To fix, either initialize:let value ="initial";// Or use definite assignment assertion:let value!:string;
• The ! is a promise to TypeScript that we'll assign a value before using it • Use of ! should be avoided as it bypasses TypeScript's safety checks
Published
Author
Nived Hari
System Analyst
When working with routes in a Rails application that includes an engine, route references need to be scoped appropriately based on where they are being called: • Referencing engine routes from outside the engine: Prefix the route with the engine's name. For example, use engine_name.some_route_path (e.g., rapidfire.surveys_path) to access routes within the engine. • Referencing routes from another engine: Use the other engine's name as a prefix, similar to referencing routes from outside. This naming ensures the correct routing context and prevents conflicts when multiple engines or the main application define similar paths.
#CU6U0R822 #routes
Published
Author
Nived Hari
System Analyst
Form Objects in Rails Form objects are a pattern that is used to encapsulate logic for managing and validating form data. They act as an intermediary between the view and the model layer, they simplify the handling of complex forms, particularly when working with complex forms that don't map to a single active record model. Why use form objects? In typical rails applications, forms are directly tied to active record models. This is ok when the forms are simple, but this can cause problem when complexity increases such as, when forms interact with multiple models In these kind of scenarios, we can encapsulate the corresponding logic into a single class which acts like an active record model which is easier to maintain.
Example form object app/forms/route_request_form.rb
Code
classUserProfileFormincludeActiveModel::Model # Attributesaccessiblefortheformobject.attr_accessor :user_name, :email, :profile_bio, :profile_agevalidates :user_name, :email, presence: truevalidates :profile_age, numericality: { only_integer:true, greater_than:0 } def savereturnfalse unless valid? #a single transaction for multiple operations ActiveRecord::Base.transaction do user =User.create!(name: user_name, email: email)user.create_profile!(bio: profile_bio, age: profile_age) endtrue # Return trueif all operations succeed. rescue ActiveRecord::RecordInvalidfalse # Return falseif the save process fails. endend
Using it in controller
Code
classUsersController < ApplicationControllerdefnew @form=UserProfileForm.newenddefcreate @form=UserProfileForm.new(user_profile_form_params)if @form.saveredirect_toroot_path,notice:"User created successfully!"elserender:new,status::unprocessable_entityendendprivatedefuser_profile_form_paramsparams.require(:user_profile_form).permit(:user_name,:email,:profile_bio,:profile_age)endend
#ruby_on_rails #form_objects
Published
Author
Sagar Ghorse
* *Convert .pem certificate into .pfx To convert a .pem certificate to .pfx, follow these steps: 1. Ensure you have OpenSSL installed. 2. Prepare the required files: ◦ .pem certificate file (certificate.pem) ◦ Private key file (privatekey.pem) ◦ (Optional) CA chain file (ca-chain.pem) 3. Run the following command to create the .pfx file:
4. When prompted, enter a password to secure the .pfx file. 5. Verify the .pfx file using:
Code
openssl pkcs12 -info -incertificate.pfx
This process combines the certificate, private key, and CA chain (if provided) into a .pfx file, which is commonly used for secure applications like Windows servers or browser-based authentication. #Certificates #SSL&TLS
Published
Author
Sagar Ghorse
Convert .pem certificate into .pfx To convert a .pem certificate to .pfx, ensure you have OpenSSL installed and have your .pem certificate file, private key file, and optionally a CA chain file ready. Use the command:
Published
Author
Nitturu Baba
System Analyst
Optimizing Validations with Caching
When we have a Member model where each user has a specific number of coins. When performing operations like capturing or deducting coins, we want to validate:
1. The user exists or not. 2. The user has enough coins to complete the operation. The basic validation will look like this (with dry-validation gem)
Code
classCoinsValidator < Dry::Validation::Contractparamsdorequired(:user).filled(:integer)required(:coins).filled(:integer, gt?:0)endrule(:user) domember=Member.find_by(unique_id:value) // querying database for member detailskey.failure("does not exist") ifmember.nil?endrule(:coins,:user) domember=Member.find_by(unique_id:values[:user]) // querying database for member detailsifmember&&member.coins < values[:coins]key(:coins).failure("are insufficient")endendend
But the problem here is, We query the database twice to fetch the same Member object once in the :user rule and again in the :coins rule. This redundant querying increases database load and slows down validation, especially in high-traffic applications.
To avoid redundant queries, we can cache the Member object using the values hash provided by the dry-validation gem. The values hash allows us to store intermediate results, making them accessible to other validation rules. The optimized code looks like this:
Code
classCoinsValidator < Dry::Validation::Contractparamsdorequired(:user).filled(:integer)required(:coins).filled(:integer, gt?:0)endrule(:user) dovalues[:member] =Member.find_by(unique_id:value) // Caching the member objectkey.failure("does not exist") ifvalues[:member].nil?endrule(:coins) domember=values[:member] // accessing the cached Member from values[:member] rather than querying the database again.ifmember&&member.coins < valuekey.failure("are insufficient")endendend
#ruby on rails
Published
Author
Amber Srivastava
Mocking Timers for Controlled Testing
If your code uses setTimeout or setInterval, Jest's timer mocking lets you fast-forward time. Example: Using jest.useFakeTimers()
Code
jest.useFakeTimers();test("delayed greeting is sent after 3 seconds", () => {constcallback=jest.fn();setTimeout(() =>callback("Hello!"),3000);jest.runAllTimers();expect(callback).toHaveBeenCalledWith("Hello!");});
#CCT1JMA0Z # testing #jest
Published
Author
Syed Sibtain
System Analyst
In Ruby, attr_reader and attr_accessor are used to create getter and setter methods for class attributes. These are part of a group of methods (attr_* methods) that make it easier to create getter and setter methods for class attributes.
attr_reader: Creates a getter method, allowing read-only access to an instance variable.
Furthermore, using attr_reader and attr_accessor promotes encapsulation by controlling how the attributes of a class are accessed and modified.
#ruby #rubyonrails
Published
Author
Amber Srivastava
------------------------- useFieldArray hook in react-hook-form ------------------------- The useFieldArray hook is part of react-hook-form and is used for handling dynamic fields in forms, such as arrays of inputs that can be added or removed dynamically. For example, if you have a list of items (like questions, tasks, or other fields) that can be added, removed, or reordered during form submission, useFieldArray is the ideal solution to manage that dynamic behaviour without manually managing the state of each individual field.
How useFieldArray works: • fields: An array of objects, where each object represents a field in the array. • append: A function to add new fields to the array. • remove: A function to remove fields from the array. • update: A function to update an individual field in the array. Example:-
Code
import { useForm, useFieldArray } from "react-hook-form";function DynamicForm() {const { register, control, handleSubmit, formState: { errors } } = useForm({defaultValues: {questions: [{ question:"" }], }, });// UseFieldArray to handle the questions array dynamicallyconst { fields, append, remove } = useFieldArray({control,name:"questions", // Name of the array in the form's state });const onSubmit = (data:any) => {console.log(data); // Submitting form data with dynamic fields };return (<form onSubmit={handleSubmit(onSubmit)}> {fields.map((item,index) => (<div key={item.id}><input {...register(`questions.${index}.question`)} // Register each question dynamicallydefaultValue={item.question} // Set default value for each item in the array/> {errors.questions?.[index]?.question && (<span>{errors.questions[index]?.question.message}</span>)}<button type="button" onClick={() => remove(index)}>Remove</button></div>))}<button type="button" onClick={() => append({ question:"" })}>Add Question</button><button type="submit">Submit</button></form>);}
Key Points: 1. name: The name prop in useFieldArray points to the field array in your form state (in this case, questions). 2. fields: This array holds the current data of the dynamic fields. Each item corresponds to a field in the form array. 3. append: This method is used to add a new item to the array. You can pass the new data for the item when appending. 4. remove: This method is used to remove an item by its index. When to use useFieldArray: • Dynamic Forms: When you have a form where the number of fields can change over time, such as adding/removing questions, tasks, team members, etc. • Nested Fields: When you have an array of objects (e.g., an array of questions, where each question has a title and description). Advantages: • It reduces the need for manual state management when adding/removing fields. • It integrates seamlessly with react-hook-form to handle validations and form submission. • It improves performance by avoiding unnecessary re-renders when fields are added or removed. #CCT1JMA0Z #useForm #react-hook-form
Published
Author
Ayasha Pandey
System Analyst
Slack's chat.deleteScheduledMessage API allows you to delete messages that were scheduled using chat.scheduleMessage but have not yet been sent.
Code
const response = await slackClient.chat.deleteScheduledMessage({channel:channelId, {// ID of the channel where the message was scheduled }scheduled_message_id:scheduledMessageId, {// ID of the scheduled message to delete}});
#slack #api
Showing 11 to 13 of 82 results
Ready to Build Something Amazing?
Codemancers can bring your vision to life and help you achieve your goals