banner image 1 banner image 2

Fascinating Features of Rails 7

March 2, 2023
6 mins
command
blog-img 1
Vendhan P J
Author

This article explains to you the features that we use very often in rails.

By Vendhan P J — “ Code Fella


The Fascinating Science of New Features for Ruby on Rails
The Fascinating Science of New Features for Ruby on Rails

Ruby on Rails, sometimes referred to as rails, is a server-side web application development framework. It is built in the Ruby programming language. It supports the model-view-controller (MVC) architecture, which gives databases, web pages, and web services a basic structure. The usage of additional well-known software engineering patterns and paradigms, such as:

  • Don’t Repeat Yourself (DRY): It is a principle of software development to reduce the repetition of information or codes.
  • Convention Over Configuration (CoC): It provides many opinions on the best way to do many things in a web application.

The Connection Between New Features for Ruby on Rails and Happiness

  • Database Layer encryption
  • Comparison Validator
  • Node.js and Webpack are not necessary
  • Invert Where method
  • Retry jobs indefinitely
  • Named Variants

Let us See One by One Is Out. Here’s What’s In

1. Database Layer encryption

class Message < ApplicationRecord
encrypts :text
end

Similar to every other characteristic, the encrypted attributes exist. Your application and its database will be automatically encrypted and decrypted by Rails 7.

Declaration of Encrypted Attributes

class Article < ApplicationRecord
encrypts :title
end

The library will transparently encrypt these attributes before saving them in the database and will decrypt them upon retrieval:

article = Article.create title: "Encrypt it all!"
article.title # => "Encrypt it all!"

But, under the hood, the executed SQL looks like this:

INSERT INTO `articles` (`title`) VALUES
('{\"p\":\"n7J0/ol+a7DRMeaE\",\"h\":{\"iv\":\"DXZMDWUKfp3bg/Yu\",\"at\":\
"X1/YjMHbHD4talgF9dt61A==\"}}')

Key Management in encryption

Important suppliers put essential management methods into action. Key providers can be configured globally or per attribute.

Built-in Key Providers

a. DerivedSecretKeyProvider
A key provider that will supply keys generated by PBKDF2 from the specified passwords.

config.active_record.encryption.key_provider = 
ActiveRecord::Encryption::DerivedSecretKeyProvider.new(["some passwords",
"to derive keys from. ", "These should be in", "credentials"])

b. EnvelopeEncryptionKeyProvider

Each data encryption process produces a random key.

It encrypts the data key using a primary key defined in the credential active record.encryption.primary key and saves it with the data. By adding this to your application.rb, you may configure Active Record to utilize this key provider

config.active_record.encryption.key_provider = 
ActiveRecord::Encryption::EnvelopeEncryptionKeyProvider.new

Custom Key Providers

In an initializer, you can define a custom key provider for more extensive key-management schemes:

ActiveRecord::Encryption.key_provider = MyKeyProvider.new

A key provider must implement this interface:

class MyKeyProvider
def encryption_key
end
def decryption_keys(encrypted_message)
end
end

Both methods return ActiveRecord::Encryption::Key objects:

  • encryption_key returns the key used for encrypting some content
  • decryption keys return a list of potential keys for decrypting a given message

2. Comparison Validator

The comparison validator validates the state of the object before it is going to store in the database. Considering all its presence, uniqueness, numerical properties, and validity of the particular data it has been checked properly.

class Post < ApplicationRecord
validates :end_date, date: { after: Proc.new { Date.today } }
validates :end_date, date: { after: :start_date }
end

If we want to validate the end_date, we have to use the custom_validator or otherwise we can use gem_validator.

After Rails 7 onwards :

class Post < ApplicationRecord
validates_comparison_of :end_date, greater_than: -> { Date.today }
validates :end_date, greater_than: :start_date
end

3. Node.js and Webpack are not necessary

The usage of npm packages is not required by developers for Webpack and Node Js. There would be several processes involved in transpiring ES6 and Babel, followed by bundling. The importmap-rails gem now allows developers to import maps. Moreover, you may use ./bin/importmap to update, pin, or unpin dependencies rather than creating code for package.json and installing dependencies using yarn or npm.

In the new version of rails ( 7 ), the package importmap-rails will be added to your gem file by default when you are creating your rails application. It is designed to be used for javascript CDNs for NPM package dependencies. You can use the ./bin/importmap command that’s added as part of the install to pin, unpin, or update npm packages in your import map.

For example- to install date-fns:

$ ./bin/importmap pin date-fns

This will automatically include a line in config/importmap.rb like: in “date-fns”, to: “https://ga.jspm.io/npm:date-fns@2.27.0/esm/index.js"

And, in your javascript, you continue to write codes like you used to.

import { formatDistance, subDays } from 'date-fns'
formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

Because there is no interaction between the code you write and how the browser interprets it, you must keep this in mind when using this structure. This is alright because the majority of important browsers now support ES6. Just Typescript and JSK need to be translated into JS before use.

Developers can also use webpack , rollup, esbuild on their applications by using the below command:

$ ./bin/rails javascript:install:[esbuild|rollup|webpack] 

4. Invert Where method

Invert_where method to the ApplicationRecord used to invert all the defined scope conditions.

Before

class User < ApplicationRecord
scope :verified, -> { where(email_verified: true, phone_verified:
true) }
scope :unverified, -> { where.not(email_verified: true,
phone_verified:true) }

scope :with_verified_email, -> { where(email_verified: true) }
scope :with_unverified_email, -> { where.not(email_verified: true) }
end

After Rails 7 :

class User < ApplicationRecord
scope :verified, -> { where(email_verified: true, phone_verified: true)
}

scope :with_verified_email, -> { where(email_verified: true) }
end

Instead of creating unverified and with_unverified_email scopes with negating conditions, we can just chain invert_where to verified and with_verified_email scopes.

5. Retry jobs indefinitely

With the ActiveJob framework, Rails 7 adds a counter-failure mechanism. This is an indefinite job retry feature that addresses the many reasons why queued jobs fail. Some of these reasons include logical problems in the code, database failures, network difficulties, and queue malfunctions.

class AlertNotification < ActiveJon::Base
retry_on AlwaysRetryException, attempts: :unlimited
def perform()
# send an alert to user
end
end

We supply the :unlimited value to the attempted argument of the retry on a function which signals that the task should always be re-enqueued in case of failures.

6. Named Variants

You can name variants using ActiveStorage in the latest Ruby on Rails 7.

class User < ApplicationRecord
has_one_attached :avatar do |attachable|
attachable.variant :thumb, resize: "100x100"
end
end

#Call avatar.variant(:thumb) to get a thumb variant of an avatar:
<%= image_tag user.avatar.variant(:thumb) %>

Conclusion

For a comprehensive list of bug fixes, enhancements, and updates, see the Rails 7 release notice. These are not exhaustive but will be updated at some time. If you're using Rail 6 or earlier, bear in mind that when Ruby on Rails 7 is published, Rail 6.1 will no longer get bug fixes. You may now upgrade to Rail 7 to obtain the most recent upgrades and features.


References :

[embed]https://guides.rubyonrails.org/7_0_release_notes.html[/embed][embed]https://guides.rubyonrails.org/7_0_release_notes.html[/embed][embed]https://guides.rubyonrails.org/7_0_release_notes.html[/embed][embed]https://guides.rubyonrails.org/7_0_release_notes.html[/embed]

Meet the team!

Author

Vendhan P J

Editor

Seema Jain


We at CaratLane are solving some of the most intriguing challenges to make our mark in the relatively uncharted omnichannel jewellery industry. If you are interested in tackling such obstacles, feel free to drop your updated resume/CV to careers@caratlane.com!
blog-img 2

Discussions

blog-img 3
5 mins
May 17, 2023
Sharing Data Between Controllers: Best Practices S...

This article will help you to understand the diffe

By Naveen C

blog-img 3
5 mins
March 21, 2023
Understanding Auto Layout and Constraints in Swift...

This article gives you an easy way of understandin

By Ramasamy P