Saeloun Blog

https://blog.saeloun.com/

Ruby on Rails and ReactJS consulting company. We also build mobile applications using React Native

フィード

記事のアイキャッチ画像
What Is New In Ruby 3.4
Saeloun Blog
It’s official, Ruby 3.4 first release is available, bringing a wave of excitement to the Ruby community.In this blog, we will go through the latest features, enhancements, and bugfixes introduced in the Ruby 3.4Prism is the new default parserRuby 3.4 switches the default parser from parse.y to Prism, which was introduced in Ruby 3.3 as a new parser designed for better maintainability, error tolerance, and performance.To use the conventional parser, use the command-line argument --parser=parse.y. Feature #20564.Garbage CollectionRuby 3.4 introduced several notable features and enhancements related to its garbage collection (GC) system, aimed at improving performance and flexibility. Here are the key updatesRuby 3.4 allows us to dynamically load different GC implementations. Enable it by configuring Ruby with --with-modular-gc at build time and load GC libraries at runtime with the RUBY_GC_LIBRARY environment variable. Feature #20351.The default GC is now separated into its own library,
20日前
記事のアイキャッチ画像
Rails 8 Adds if_not_exists Option On The add_enum_value.
Saeloun Blog
Rails 7 added support for custom enum types in PostgreSQL with introduction of create_enum to add a new enum type and t.enum to add a column.Rails 7.1 has extended the ability to rename an enum, add enum value and rename enum value for the Postgres database adapter.The add_enum_value method provides a straightforward way to add new values to a PostgreSQL enum type without needing to execute raw SQL.class AddEnumToArticles < ActiveRecord::Migration[7.2] def change create_enum :status, ["draft", "published", "archived", "trashed"] safety_assured do change_table :articles do |t| t.enum :current_status, enum_type: "status", default: "draft", null: false end end endendclass AddReviewToArticleStatus < ActiveRecord::Migration[7.2] def change add_enum_value :status, 'review' endendBeforeWhen we use add_enum_value, PostgreSQL checks for duplicates and raises a PG::DuplicateObject error if a value already exists. ActiveRecord captures this as ActiveRecord::StatementInvalid when trying to add a d
1ヶ月前
記事のアイキャッチ画像
Rails 8 Adds Parameters#expect To Safely Filter And Require Params.
Saeloun Blog
Rails 8 introduces params#expect, a new method that enhances parameter handling by filtering parameters based on expected types. This reduces errors caused by tampering or invalid input.BeforeActionController parameters allows us to choose which attributes should be permitted with the help of require and permit. By default, the recommended way of handling parameters in Rails works fine. Until someone using our app starts messing with the parameters and causing 500 errors.params.require(:post).permit(:title, :summary, categories: [:name])http://localhost:3000/?post[title]=Hello World#=> {"title"=>"Hello World"}Passing a String Instead of a HashIf someone tampered params by passing string instead of hash. This throws NoMethodError because the permit is called on string.http://localhost:3000/?post=Hello World#=> {"post"=>"Hello World"}Completed 500 Internal Server Error in 28ms (ActiveRecord: 0.0ms (0 queries, 0 cached) | GC: 23.3ms)NoMethodError undefined method `permit' for "Hello World
1ヶ月前
記事のアイキャッチ画像
Rails 8 Allows drop_table To Accept An Array Of Table Names.
Saeloun Blog
ActiveRecord provides drop_table method to drop a table from database using migration.class DropPosts < ActiveRecord::Migration[7.2] def change drop_table :posts endendBeforeIf we want to drop multiple tables in one call using drop_table, ActiveRecord did not provide direct support.So we have to either call drop_table multiple times or use raw SQL.class DropMultipleTables < ActiveRecord::Migration[7.2] def change drop_table :users drop_table :posts drop_table :comments endclass DropMultipleTables < ActiveRecord::Migration[7.2] def change [:users, :posts, :comments].each do |table_name| drop_table table_name end endendActiveRecord::Base.connection.execute 'DROP TABLE users, posts, comments'AfterRails 8 adds support to drop multiple tables in one call using drop_table on ActiveRecord.drop_table :table1, :table2, :table3With this update, Rails allows drop_table to accept an array of table names.class DropMultipleTables < ActiveRecord::Migration[8.0] def change drop_table :users, :posts, :
1ヶ月前
記事のアイキャッチ画像
Implementing Passwordless Authentication with WebAuthn in Rails
Saeloun Blog
What is Passwordless authentication?Passwordless authentication is an authentication method that verifies users identity and grant access to a site or system without using password. Instead, users can authenticate using methods like:Biometrics: Face ID, Touch IDHardware tokens: Devices like YubiKeysDigital tokens: Generated by authenticator appsMagic links: Sent to the user’s emailThis method enhances security and simplifies the login process by eliminating password vulnerabilities.What is WebAuthn?WebAuthn (Web Authentication API) is a W3C and FIDO standard that provides strong, passwordless authentication using public-key cryptography. It replaces passwords and SMS-based methods with secure, user-friendly solutions.How Does WebAuthn Work?1) Public Key Generation (Registration): During registration, the authenticator generates a public-private key pair. The public key is sent to the server and stored, while the private key stays securely on the authenticator.2) Private Key Usage (Auth
1ヶ月前
記事のアイキャッチ画像
Rails 8 Adds Ability To Use Multiple Rate Limits Per Controller.
Saeloun Blog
Rate limiting is a crucial technique for managing server traffic, enhancing performance, and bolstering security. By controlling the number of incoming requests over a specific time, it protects systems from abuse and overload.BeforeIn Rails 7.2, rate limiting was introduced to Action Controller, enabling developers to limit requests to specific actions within a defined time period.class PostsController < ApplicationController rate_limit to: 10, within: 3.minutes, only: :createendHowever, the limitation here was the inability to define multiple rate limits for different use cases within the same controller.AfterRails 8 introduces support for multiple rate limits per controller. This enhancement allows developers to apply distinct rate limits to the same action or across multiple actions by using the name: option.class PostsController < ApplicationController rate_limit to: 3, within: 2.seconds, name: "short-term", only: :create # Long-term limit for general access rate_limit to: 10, wit
1ヶ月前
記事のアイキャッチ画像
Rails 7.2 Added Support For Explain Method To ActiveRecord::Relation.
Saeloun Blog
When optimizing database queries in Rails, it’s essential to understand how the database plans to execute a query. Rails provides a built-in method, ActiveRecord::Relation#explain, to analyze and display a query’s execution plan. The output mimics the format of a database shell, offering valuable insights into query performance and potential bottlenecks.BackgroundBefore Rails 7.1, the explain method provided basic query execution plans. Rails 7.1 introduced options like analyze and verbose to offer deeper insights into query performance. You can learn more about this in our blog post.With Rails 7.2, the feature has been further enhanced. The explain method now supports pluck, count, first, and other methods directly on an ActiveRecord::Relation, making it even more powerful and user-friendly.What Is ActiveRecord::Relation#explain?The explain method runs the database’s EXPLAIN command on the query triggered by the relation and returns the result. This allows us to:See how the database w
2ヶ月前
記事のアイキャッチ画像
Rails 7.1 Introduces By Argument For increment_counter And decrement_counter Methods.
Saeloun Blog
Counter caching is a common practice in Rails, used to keep track of counts such as the number of comments on a post or likes on a video. Rails 7.1 provides built-in methods like increment_counter and decrement_counter for updating counters without loading records into memory. However, before Rails 7.1, these methods could only update by a value of 1.In scenarios where counter caches needed to be incremented or decremented by amounts greater than 1, such as recalculating counts or applying bulk updates, we often turned to workarounds or relied on gems like counter_culture. With the introduction of the by argument in Rails 7.1, managing these cases is now much simpler.Before Rails 7.1:By default, increment_counter and decrement_counter only supported updates by 1. To increment or decrement by custom amounts, we had to:1) Use Raw SQL:Article.where(id: 10).update_all("comments_count = comments_count + 5")This was efficient but required direct SQL manipulation, reducing code clarity.2) Fet
2ヶ月前
記事のアイキャッチ画像
Rails 7.1 Adds Rails.application.deprecators Method
Saeloun Blog
Deprecations are warnings that notify developers about features slated for removal or change in future versions. They ensure a smooth transition to newer alternatives while maintaining compatibility.BeforeBefore Rails 7.1, deprecations were managed globally through ActiveSupport::Deprecation, with no way to differentiate or individually configure different types of deprecations and it lacked flexibility for managing multiple deprecations.class User < ApplicationRecord def full_name ActiveSupport::Deprecation.warn("The `full_name` method will be removed in the next major release.") endenduser = User.firstuser.full_nameDEPRECATION WARNING: The `full_name` method will be removed in the next major release. (called from <main> at (irb):2)DEPRECATION WARNING: Calling warn on ActiveSupport::Deprecation is deprecated and will be removed from Rails (use your own Deprecation object instead) (called from full_name at /app/models/user.rb:3)=> "DEPRECATION WARNING: The `full_name` method will be re
2ヶ月前
記事のアイキャッチ画像
Rails 7.1 Allows Validators To Accept Lambdas Without Record Argument
Saeloun Blog
Rails validations are a key feature for ensuring the integrity of the data being saved to the database. They allow us to define rules for model attributes, such as requiring a value, ensuring uniqueness, or excluding specific values. Rails also allows us to use custom logic for validations by using blocks or callable objects like lambdas.What Is a Lambda in Ruby?A lambda is a type of Proc object in Ruby with stricter rules.Argument checking: A lambda ensures the number of arguments passed matches the number expected. If not, it raises an error.Return behavior: A lambda returns control back to where it was called, instead of exiting the enclosing method like a regular proc.print_value = ->(x) { "Value: #{x}" }print_value.call(10) # Works fineprint_value.call(10, 20) # Raises an ArgumentErrorBefore Rails 7.1In earlier versions of Rails, lambdas used in validations required an argument, even if the argument was not needed. Without this, Rails would raise an ArgumentError.class User < Appl
2ヶ月前