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.
Dec 17, 2024
When working with paginated data in Ruby on Rails, we might encounter situations where we need to paginate an array rather than an Active Record collection. The
Require the Pagy Extras Array:
And then use the
#rubyonrails #pagination #pagy
pagy
gem provides an efficient and flexible way to handle pagination, and it includes an extras/array
feature specifically for arrays.Require the Pagy Extras Array:
# config/initializers/pagy.rb
require "pagy/extras/array"
And then use the
pagy_array
method to paginate your array in the controller
def index
// some code
@pagy, @purchase_order_attachments = pagy_array(orders_with_attachments, items: params[:limit] || 10)
end
#rubyonrails #pagination #pagy
Syed Sibtain
System Analyst
Dec 3, 2024
In Python,
Example:
Output:
dir()
lists the attributes and methods of an object, such as a class or instance.Example:
class MyClass:
class_variable = "Class Variable"
def __init__(self):
self.instance_variable = "Instance Variable"
def my_method(self):
pass
obj = MyClass()
print(dir(obj))
Output:
dir(obj)
shows a list of attributes (class_variable
, instance_variable
) and methods (my_method
), along with special methods (e.g., __init__
). It helps explore what’s available in an object.Adithya Hebbar
System Analyst
Nov 29, 2024
Test SSH connection detailed logs to debug #ssh #CCTJN6PK4
This will output detailed logs
ssh -vT "git@gitlab.com"
This will output detailed logs
nisanth
Nov 29, 2024
Definite Assignment Checks in TypeScript 5
• Before TypeScript 5:
• After TypeScript 5:
• The
• Use of
• Before TypeScript 5:
let value: string;
console.log(value); // TS4.x: This was allowed but could lead to runtime undefined
• After TypeScript 5:
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 checksAshwani Kumar Jha
Senior System Analyst
Nov 28, 2024
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
• 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
• 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
Nived Hari
System Analyst
Nov 28, 2024
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
Using it in controller
#ruby_on_rails #form_objects
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
class UserProfileForm
include ActiveModel::Model
# Attributes accessible for the form object.
attr_accessor :user_name, :email, :profile_bio, :profile_age
validates :user_name, :email, presence: true
validates :profile_age, numericality: { only_integer: true, greater_than: 0 }
def save
return false 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)
end
true # Return true if all operations succeed.
rescue ActiveRecord::RecordInvalid
false # Return false if the save process fails.
end
end
Using it in controller
class UsersController < ApplicationController
def new
@form = UserProfileForm.new
end
def create
@form = UserProfileForm.new(user_profile_form_params)
if @form.save
redirect_to root_path, notice: "User created successfully!"
else
render :new, status: :unprocessable_entity
end
end
private
def user_profile_form_params
params.require(:user_profile_form).permit(:user_name, :email, :profile_bio, :profile_age)
end
end
#ruby_on_rails #form_objects
Nived Hari
System Analyst
Nov 28, 2024
*
*Convert .pem certificate into .pfx
To convert a
1. Ensure you have OpenSSL installed.
2. Prepare the required files:
◦
◦ Private key file (
◦ (Optional) CA chain file (
3. Run the following command to create the
4. When prompted, enter a password to secure the
5. Verify the
This process combines the certificate, private key, and CA chain (if provided) into a
#Certificates #SSL&TLS
*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:
openssl pkcs12 -export -out certificate.pfx -inkey privatekey.pem -in certificate.pem -certfile ca-chain.pem
4. When prompted, enter a password to secure the
.pfx
file.5. Verify the
.pfx
file using:
openssl pkcs12 -info -in certificate.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
sagar.ghorse
Nov 28, 2024
Convert .pem certificate into .pfx
To convert a
Use the command:
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:
sagar.ghorse
Nov 26, 2024
Optimizing Validations with Caching
When we have a
1. The user exists or not.
2. The user has enough coins to complete the operation.
The basic validation will look like this (with
But the problem here is, We query the database twice to fetch the same
To avoid redundant queries, we can cache the
The optimized code looks like this:
#ruby on rails
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)
class CoinsValidator < Dry::Validation::Contract
params do
required(:user).filled(:integer)
required(:coins).filled(:integer, gt?: 0)
end
rule(:user) do
member = Member.find_by(unique_id: value) // querying database for member details
key.failure("does not exist") if member.nil?
end
rule(:coins, :user) do
member = Member.find_by(unique_id: values[:user]) // querying database for member details
if member && member.coins < values[:coins]
key(:coins).failure("are insufficient")
end
end
end
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:
class CoinsValidator < Dry::Validation::Contract
params do
required(:user).filled(:integer)
required(:coins).filled(:integer, gt?: 0)
end
rule(:user) do
values[:member] = Member.find_by(unique_id: value) // Caching the member object
key.failure("does not exist") if values[:member].nil?
end
rule(:coins) do
member = values[:member] // accessing the cached Member from values[:member] rather than querying the database again.
if member && member.coins < value
key.failure("are insufficient")
end
end
end
#ruby on rails
Nitturu Baba
System Analyst
Nov 21, 2024
Mocking Timers for Controlled Testing
If your code uses
Example: Using
#CCT1JMA0Z # testing #jest
If your code uses
setTimeout
or setInterval
, Jest's timer mocking lets you fast-forward time.Example: Using
jest.useFakeTimers()
jest.useFakeTimers();
test("delayed greeting is sent after 3 seconds", () => {
const callback = jest.fn();
setTimeout(() => callback("Hello!"), 3000);
jest.runAllTimers();
expect(callback).toHaveBeenCalledWith("Hello!");
});
#CCT1JMA0Z # testing #jest
amber.srivastava
Showing 6 to 8 of 77 results
Ready to Build Something Amazing?
Codemancers can bring your vision to life and help you achieve your goals
- Address
2nd Floor, Zee Plaza,
No. 1678, 27th Main Rd,
Sector 2, HSR Layout,
Bengaluru, Karnataka 560102 - Contact
hello@codemancers.com
+91-9731601276