author avatar

giritharan

Tue Jan 21 2025

Rails Inflections:
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 footfeet, 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
author avatar

ashwanikumarjha

Fri 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:


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
author avatar

syedsibtain

Mon 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.



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
author avatar

vaibhav.yadav

Fri Jan 10 2025

Using DISTINCT ON in PostgreSQL

When 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
author avatar

satya

Thu Jan 09 2025

ActiveSupport::CurrentAttributes provides a thread-isolated attributes singleton, perfect for request-specific data like current user, role, or locale.
create a current.rb in models directory and add the attributes we want to set


class Current < ActiveSupport::CurrentAttributes
  attribute :role
end


then in application controller we can set it like this


class ApplicationController < ActionController::Base  
  before_action :set_current_attributes

  def set_current_attributes
    Current.role = session[:role]
    // ... other attributes
  end
end


now in your application we can directly access and use like Current.role

#CU6U0R822 #rails-current-attributes
author avatar

aditya.vishwakarma

Fri Dec 27 2024

Mise

Mise is a fast, lightweight (thanks to Rust :happy_pepe:), language agnostic version manager that can be used instead of having separate language based version managers like rbenv for Ruby, npm for Node.js and Pyenv for Python etc.

Installing a Ruby version globally is as simple as follows:


mise use -g ruby@3


Installing mise is as easy as following in MacOS


curl https://mise.run | sh


Proceed with following to configure the Shell Initialisation


echo 'eval "$(~/.local/bin/mise activate)"' >> ~/.zshrc


Reload the shell configuration changes in current tab


source ~/.zshrc


#mise #ruby-version-manager #version-manager #C04HPTKNZ8R #ruby #python #CCT1JMA0Z
author avatar

nived.hari

Sun Dec 22 2024

mattr_accessor is a Rails utility method that creates a class-level accessor for a variable.
When we define mattr_accessor for a variable, it creates
1. A getter method for the class.
2. A setter method for the class.
Eg:


class MyClass
  mattr_accessor :my_variable
end


This is equivalent to:


class MyClass
  @my_variable = nil

  def self.my_variable
    @my_variable
  end

  def self.my_variable=(value)
    @my_variable = value
  end
end


It also works on module-level classes, which makes it particularly useful for defining global configuration in gems.

#CU6U0R822
author avatar

ayushsrivastava

Wed Dec 18 2024

accepts_nested_attributes_for is a Rails method that allows you to easily manage the creation, updating, and destruction of associated models through the parent model's attributes. This is particularly useful when you have nested forms or when you want to handle multiple models in a single operation (e.g., creating or updating a User and its associated Profile in one form submission).



class User < ApplicationRecord
  has_one :profile
  accepts_nested_attributes_for :profile
end


Given the User model has a has_one :profile association, and you want to create or update a User and their Profile at the same time, you can use accepts_nested_attributes_for to pass attributes for both models:


user_params = {
  name: "John Doe",
  profile_attributes: { bio: "Developer", age: 30 }
}

user = User.create(user_params)


In this example, Rails will create both a new User and a new Profile with the attributes provided in profile_attributes.
#CU6U0R822
author avatar

syedsibtain

Tue 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 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
author avatar

adithya.hebbar

Tue Dec 03 2024

In Python, 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.

Showing 1 to 5 of 73 results