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.
Feb 20, 2025
Collection caching is a way to speed up rendering multiple items on a page by storing their HTML in cache.
How it works:
1. When we use <%= render partial: 'products/product', collection: @products, cached: true %>, Rails checks if each product's HTML is already stored in the cache.
2. If a product’s HTML is found in the cache, Rails loads it quickly instead of rendering it again.
3. If a product’s HTML is not in the cache, Rails will render it, store it in the cache, and use it next time.
4. The big advantage: Rails fetches all cached products at once (instead of one by one), making it much faster.
#CU6U0R822 #caching #collection_caching
How it works:
1. When we use <%= render partial: 'products/product', collection: @products, cached: true %>, Rails checks if each product's HTML is already stored in the cache.
2. If a product’s HTML is found in the cache, Rails loads it quickly instead of rendering it again.
3. If a product’s HTML is not in the cache, Rails will render it, store it in the cache, and use it next time.
4. The big advantage: Rails fetches all cached products at once (instead of one by one), making it much faster.
#CU6U0R822 #caching #collection_caching
Puneeth kumar
System Analyst
Feb 19, 2025
When testing with Capybara, you might need to scroll an element into view before interacting with it. Instead of using JavaScript like:
You can use Capybara's built-in method:
This is available in
Capybara 3.26+
and is the preferred way to ensure visibility before clicking or interacting with an element.
#capybara #CU6U0R822 #C041BBLJ57G
page.execute_script("arguments[0].scrollIntoView(true)", button)
You can use Capybara's built-in method:
scroll_to(button) # Scrolls to the element
This is available in
Capybara 3.26+
and is the preferred way to ensure visibility before clicking or interacting with an element.
#capybara #CU6U0R822 #C041BBLJ57G
Nived Hari
System Analyst
Feb 19, 2025
In JavaScript, you can use
Example:
• Case-insensitive
• Accent-insensitive
No need for
second argument is
Sensitivity is the behaviour of the comparison
#stimulus #JavaScript #StringComparison
localeCompare
with { sensitivity: "base" }
to compare strings without considering case or accents.Example:
"Test".localeCompare("test", undefined, { sensitivity: "base" }) === 0; // ✅ True
"café".localeCompare("cafe", undefined, { sensitivity: "base" }) === 0; // ✅ True
"Hello".localeCompare("HELLO", undefined, { sensitivity: "base" }) === 0; // ✅ True
• Case-insensitive
• Accent-insensitive
No need for
toLowerCase()
hacks anymore! 🎉second argument is
locale
. by giving it as "Undefined" it uses default locale of the runtime environment. We can specify as "en", "id" etc. It is used in sorting scenarios ig.Sensitivity is the behaviour of the comparison
"base" → Ignores case & accents ("café" == "cafe", "Hello" == "hello")
"accent" → Considers accents but ignores case ("café" != "cafe", "Hello" == "hello")
"case" → Considers case but ignores accents ("café" == "cafe", "Hello" != "hello")
"variant" → Considers both case & accents ("café" != "cafe", "Hello" != "he
#stimulus #JavaScript #StringComparison
Nived Hari
System Analyst
Feb 19, 2025
By default, Capybara only finds visible and interactable elements. If a button is disabled or outside the viewport, Capybara may fail to locate it.
To fix this, use:
•
•
This is useful when testing UI behaviors where buttons are conditionally enabled/disabled or require scrolling to be visible.
#CU6U0R822 #capybara #C041BBLJ57G #specs
To fix this, use:
expect(page).to have_button("Add Discrepancy", disabled: true, visible: :all)
•
disabled: true
ensures the button is actually disabled •
visible: :all
allows Capybara to find buttons that are hidden, off-screen, or disabledThis is useful when testing UI behaviors where buttons are conditionally enabled/disabled or require scrolling to be visible.
#CU6U0R822 #capybara #C041BBLJ57G #specs
Nived Hari
System Analyst
Feb 5, 2025
local_assigns :
When using partial views in Rails (like
To avoid this,
Here, the partial checks if show_projects was passed before using it. If show_projects was provided, it renders the user's projects or a message if no projects are found. If show_projects wasn't passed, nothing happens, preventing errors.
When using partial views in Rails (like
_partial.html.erb
), we might pass local variables to customize the rendering. However, if we try to use a local variable that wasn't passed, Rails will raise an error.To avoid this,
local_assigns
is a special hash that helps check if a local variable was provided when rendering the partial. Instead of directly using <%= show_projects %>
, which could cause an error if missing, we can safely check local_assigns[:show_projects]
first.
<% if local_assigns[:show_projects] %>
<%= (render @user.projects) || (render 'shared/empty_state', message: "No projects found!") %>
<% end %>
Here, the partial checks if show_projects was passed before using it. If show_projects was provided, it renders the user's projects or a message if no projects are found. If show_projects wasn't passed, nothing happens, preventing errors.
Puneeth kumar
System Analyst
Jan 27, 2025
The Rails 8.0 release introduces several new features, and among them, params#expect stands out.
In our daily work with Rails, we often rely on params#require for assignments and queries. However, params#require is more explicit than permit. Here’s an example to illustrate:
If you expect the posts parameter to contain a list of IDs, such as [{id: 1}, {id: 2}], you can define your expectations like this:
The output will be:
Now, consider a different scenario where you expect the posts parameter to have only a single hash with an ID, like this:
If you use:
It will raise the following error:
ActionController::ExpectedParameterMissing: param is missing or the value is empty or invalid: posts
In contrast, using the older params#permit:
Will not enforce your expectation of the nested parameter structure and will accept it without validation.
In our daily work with Rails, we often rely on params#require for assignments and queries. However, params#require is more explicit than permit. Here’s an example to illustrate:
params = ActionController::Parameters.new(posts: [{id: 1}])
If you expect the posts parameter to contain a list of IDs, such as [{id: 1}, {id: 2}], you can define your expectations like this:
params.expect(posts: [[:id]])
The output will be:
[
#<ActionController::Parameters {"id"=>1} permitted: true>,
#<ActionController::Parameters {"id"=>2} permitted: true>
]
Now, consider a different scenario where you expect the posts parameter to have only a single hash with an ID, like this:
params = ActionController::Parameters.new(posts: {id: 1})
If you use:
params.expect(posts: [[:id]])
It will raise the following error:
ActionController::ExpectedParameterMissing: param is missing or the value is empty or invalid: posts
In contrast, using the older params#permit:
params.permit(posts: [:id])
Will not enforce your expectation of the nested parameter structure and will accept it without validation.
Mohammad hussain
System Analyst
Jan 21, 2025
Rails Inflections:
What is it? Inflections in Rails, powered by the
Why use it? Sometimes Rails' default pluralization rules don't fit your app's needs (e.g., irregular words like
Examples
• Default Behavior:
• Irregular Inflections:
• Uncountable Words:
• Acronym Inflections:
Potential Issues:
• Default Behavior May Be Inaccurate: Without customizing, words like "tooth" become "tooths" or "milk" becomes "milks."
• Localization: Inflections are locale-specific, so customizations for one locale won't apply to others.
Best Practice: Always define rules for edge cases (irregular, uncountable, acronyms) in your
#rails-inflections #active-support #CU6U0R822
What is it? Inflections in Rails, powered by the
ActiveSupport::Inflector
module, allow customization of how words are pluralized, singularized, or treated as uncountable.Why use it? Sometimes Rails' default pluralization rules don't fit your app's needs (e.g., irregular words like
foot
→ feet
, uncountable words like milk
).Examples
• Default Behavior:
"person".pluralize # => "people"
"person".singularize # => "person"
• Irregular Inflections:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.irregular "foot", "feet"
end
// "foot".pluralize # => "feet"
• Uncountable Words:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.uncountable "milk"
end
// "milk".pluralize # => "milk"
• Acronym Inflections:
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym "HTML5"
end
// "html5".camelize # => "HTML5"
Potential Issues:
• Default Behavior May Be Inaccurate: Without customizing, words like "tooth" become "tooths" or "milk" becomes "milks."
• Localization: Inflections are locale-specific, so customizations for one locale won't apply to others.
Best Practice: Always define rules for edge cases (irregular, uncountable, acronyms) in your
config/initializers/inflections.rb
ans restart the server after changes#rails-inflections #active-support #CU6U0R822
Giritharan
System Analyst
Jan 17, 2025
EXPLAIN ANALYZE Command in PostgreSQL
1. EXPLAIN: shows the query execution plan that PostgreSQL's query planner generates for the specified query. It tells us how PostgreSQL plans to execute the query, including:
◦ What type of scan it will use (sequential scan, index scan)
◦ The estimated cost
◦ The estimated number of rows
2. ANALYZE: actually executes the query and shows the real results, including:
◦ Actual time taken
◦ Actual number of rows processed
eg:
When we will run this command, we'll see output that looks something like this:
Here in this output:
• Seq Scan on public.card:
◦ This indicates PostgreSQL is doing a sequential scan (reading the entire table)
◦ cost=0.00..11.75: unit-less value that represents PostgreSQL's estimate of how expensive the query will be
◦ rows=1: PostgreSQL estimates it will find 1 row
◦ width=180: Estimated average width of each row in bytes
◦ actual time=0.016..0.018: Actual time taken (in ms)
◦ rows=1: Actually found 1 row
◦ loops=1: The operation was performed once
• Filter: ((card_number)::text = '120000024223'::text):
◦ Shows the WHERE clause condition being applied
• Rows Removed by Filter: 100:
◦ 100 rows were checked but didn't match the condition
◦ This means the table had 101 total rows (100 filtered + 1 matching)
• Planning Time: 0.152 ms:
◦ Time taken to generate the query execution plan
• Execution Time: 0.034 ms:
◦ Actual time taken to execute the query
This can be used for:
• Debugging performance issues
• Finding bottlenecks in query performance
#PostgreSQL #query
1. EXPLAIN: shows the query execution plan that PostgreSQL's query planner generates for the specified query. It tells us how PostgreSQL plans to execute the query, including:
◦ What type of scan it will use (sequential scan, index scan)
◦ The estimated cost
◦ The estimated number of rows
2. ANALYZE: actually executes the query and shows the real results, including:
◦ Actual time taken
◦ Actual number of rows processed
eg:
EXPLAIN ANALYZE select * from public.card
where card_number='120000024223'
When we will run this command, we'll see output that looks something like this:
Seq Scan on public.card (cost=0.00..11.75 rows=1 width=180) (actual time=0.016..0.018 rows=1 loops=1)
Filter: ((card_number)::text = '120000024223'::text)
Rows Removed by Filter: 100
Planning Time: 0.152 ms
Execution Time: 0.034 ms
Here in this output:
• Seq Scan on public.card:
◦ This indicates PostgreSQL is doing a sequential scan (reading the entire table)
◦ cost=0.00..11.75: unit-less value that represents PostgreSQL's estimate of how expensive the query will be
◦ rows=1: PostgreSQL estimates it will find 1 row
◦ width=180: Estimated average width of each row in bytes
◦ actual time=0.016..0.018: Actual time taken (in ms)
◦ rows=1: Actually found 1 row
◦ loops=1: The operation was performed once
• Filter: ((card_number)::text = '120000024223'::text):
◦ Shows the WHERE clause condition being applied
• Rows Removed by Filter: 100:
◦ 100 rows were checked but didn't match the condition
◦ This means the table had 101 total rows (100 filtered + 1 matching)
• Planning Time: 0.152 ms:
◦ Time taken to generate the query execution plan
• Execution Time: 0.034 ms:
◦ Actual time taken to execute the query
This can be used for:
• Debugging performance issues
• Finding bottlenecks in query performance
#PostgreSQL #query
Ashwani Kumar Jha
Senior System Analyst
Jan 13, 2025
Shared Context in RSpec
Shared Context: A shared context in RSpec is a way to define common setup code that can be reused across multiple test examples or groups. Instead of duplicating setup code, we define it once in a shared context and include it wherever needed. It helps keep our tests DRY.
In the example, the shared context
By including the shared context with
#rspec #rubyonrails
Shared Context: A shared context in RSpec is a way to define common setup code that can be reused across multiple test examples or groups. Instead of duplicating setup code, we define it once in a shared context and include it wherever needed. It helps keep our tests DRY.
RSpec.shared_context "user and post setup", shared_context: :metadata do
let(:user) { User.create(name: "Alice") }
let(:post) { Post.create(title: "First Post", user: user) }
end
RSpec.describe "Using shared context in tests" do
include_context "user and post setup"
it "has a user with a name" do
expect(user.name).to eq("Alice")
end
it "has a post with a title" do
expect(post.title).to eq("First Post")
end
end
In the example, the shared context
user and post setup
defines let
variables for a user
and a post
.By including the shared context with
include_context
, we gain access to those let
variables in the test examples.#rspec #rubyonrails
Syed Sibtain
System Analyst
Jan 10, 2025
Using
When using
For example:
Key points:
•
•
• Additional columns in
Mistakenly not matching the
#postgres #sql #database
DISTINCT ON
in PostgreSQLWhen using
DISTINCT ON
in PostgreSQL, the columns specified in the DISTINCT ON
clause must appear first in the ORDER BY
clause and in the same order. This is a requirement to ensure PostgreSQL knows how to determine the "first" row for each distinct group.For example:
SELECT DISTINCT ON (user_id, event_name) id, user_id, event_name, inquiry_id, created_at
FROM public.persona_inquiry
ORDER BY user_id, event_name, created_at DESC;
Key points:
•
DISTINCT ON (user_id, event_name)
selects the first row for each unique (user_id, event_name)
combination.•
ORDER BY user_id, event_name
ensures that the sorting starts with the same columns as the DISTINCT ON
clause.• Additional columns in
ORDER BY
(like created_at DESC
) determine which row to pick when there are duplicates.Mistakenly not matching the
DISTINCT ON
columns with the start of the ORDER BY
clause will result in an error:SELECT DISTINCT ON expressions must match initial ORDER BY expressions
.#postgres #sql #database
Vaibhav Yadav
Senior System Analyst
Showing 6 to 8 of 79 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