Saeloun Blog

https://blog.saeloun.com/

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

フィード

記事のアイキャッチ画像
Ruby 3.4, Range#size Now Raises TypeError If The Range Is Not Iterable
はてなブックマークアイコン 1
Saeloun Blog
In Ruby, a Range is an object that represents a range of values with a defined beginning and end. It is a fundamental data structure used to express a sequence or span between two values, whether they are numeric, alphabetical, or even dates.We have two ways to define ranges.# Inclusive Range (includes both start and end values)inclusive_range = (start_value..end_value)inclusive_range = (1..5) #=> [1, 2, 3, 4, 5]# Exclusive Range (excludes the end value)exclusive_range = (start_value...end_value)exclusive_range = (1...5) # Includes 1, 2, 3, 4 (excludes 5)#=> [1, 2, 3, 4]Ruby Range#size methodReturns the number of elements in the range. Both the begin and the end of the Range must be Numeric, otherwise nil is returned.(10..20).size #=> 11(10...20).size #=> 10('a'..'z').size #=> nilBeforeWhen the begin value of Range is a Float or Rational, “the count of elements” does not make sense. Such Ranges are not iteratable, suggesting there are no such things as “elements”.Yet, Range#size of suc
4日前
記事のアイキャッチ画像
Rails 8 adds Kamal by default.
Saeloun Blog
What is Kamal?Kamal is a deployment tool developed by 37signals,designed to simplify the deployment of web applications by using Docker containers and theTraefikreverse proxy for seamless,zero-downtime deployments.BeforeBefore Rails 8, we had to manually install Kamal into our project and then do the setup.Installation:gem install kamalOr add it to the Gemfile of the project.# Gemfilegem 'kamal', require: falseand then runbundle installInitialize Kamalkamal initThis creates a default configuration file at config/deploy.yml and a .env file.AfterRails 8 now adds Kamal by default.While creating a new rails app with rails new <app_name>,an entry for kamal gem will be added in the Gemfile andtwo additional files will be created with default configuration.# Gemfilegem "kamal", require: false.env.erbconfig/deploy.ymlDefault ConfigurationHere are the contents of theconfig/deploy.yml template:# Name of your application. Used to uniquely configure containers.service: <%= app_name %># Name of the
6日前
記事のアイキャッチ画像
Ruby 3.4, No More TypeError With **nil As It Is Treated As An Empty Hash.
Saeloun Blog
In Ruby, the splat * and double splat ** operators are used for handling variable-length arguments in methods, especially when dealing with arrays and hashes.The Single Splat operator (*) constructs and spreads out Arrays.If we use it when defining a method, it constructs into an array.def example_method(*args) puts "args are: #{args}"endexample_method(3, 5, 7) # => args are: [3, 5, 7]If we use it when passing arguments as an array, it deconstructs the array into arguments.def example_method(a, b, c) puts "args are: #{a}, #{b}, #{c}"endexample_method(*[3, 5, 7]) # => args are: 3, 5, 7The double Splat operator (**) It works similarly. We can construct and spread out Hashes.If we use it when defining a method, it constructs into an hash.def example_method(**args) puts "args are: #{args}"endoptions = {x: 1, y: 2}example_method(**options) # => args are: {:x=>1, :y=>2}If we use it when passing arguments as an hash, it deconstructs the hash into arguments.def example_method(a:, b:, c:) puts
8日前
記事のアイキャッチ画像
Enhancing Data Integrity With validate_foreign_key In Rails
Saeloun Blog
Rails offers powerful tools for managing database relationships, including the use of foreign key constraints.Foreign keyForeign key constraints establish a relationship between two tables in a database, ensuring that the value in a column (the foreign key) in one table matches a value in the primary key column of another table. This relationship helps maintain referential integrity, preventing orphaned records and ensuring data consistency.BeforeLet’s assume we’re building an application that stores articles and their respective authors.We’ll have two models, Article and Author.In case of relational DB, these are linked via foreign_keys.Each article is linked to its respective author using a foreign key. This setup allows us to easily retrieve all articles associated with a particular author by querying the articles table using the foreign key.add_foreign_key(from_table, to_table, **options)Let’s add foreign key to link each article to the authoradd_foreign_key :articles, :authorsThe
13日前
記事のアイキャッチ画像
Rails Adds GitHub CI Workflow By Default To New Applications
Saeloun Blog
Continuous Integration/Continuous Deployment, also known as Continuous Delivery or CI/CD, is a software development technique that aims to automate the steps involved in integrating code changes into a shared source code repository, testing those changes, and automatically deploying those changes to target environments without the need for human intervention.It makes early error detection easier and minimises the amount of code that needs to be debugged by a developer to identify the fault’s source.It also forms the basis of contemporary DevOps operations, facilitating more fluid and agile collaboration between development and operations teams.Several well-known CI/CD solutions include AWS CodeDeploy, GitHub CI, GitLab, TeamCity, Bamboo and Jenkins.GitHub CI/CDGitHub Actions is a powerful CI/CD tool provided by GitHub that gives developers the ability to automate their processes to build, test, and release software. It provides customizable CI/CD starter workflows that are suited for d
19日前
記事のアイキャッチ画像
ActiveRecord::Base#pluck adds support for hash values in Rails 7.2
Saeloun Blog
In day-to-day life, we see many dashboards which consist of charts and reports.To build these charts or reports quickly, we required specific data fromdifferent database tables in faster queries.The ActiveRecord::Base#pluck method is used to query single or multipleattributes from the database without loading the entire record.It returns the results as an array of attribute values.User.pluck(:id, :name, :email)The above code will result in the following query:SELECT users.id, users.name, users.email FROM "users"The above query returns the following output:=> [ [1, "David Heinemeier Hansson", "[email protected]"], [2, "Rafael França", "[email protected]"], [3, "Vipul Amler", "[email protected]"] ]BeforeWe are not limited to querying fields from a single table,we can query multiple tables as well.While we can use the column names as a symbol it used to only workwhile fetching columns from a single table,but when we wanted to join multiple tableswe had to go back to the string format to mention
25日前
記事のアイキャッチ画像
Enhancing Rails Log Output with SQL Query Count
Saeloun Blog
Rails developers often faced challenges optimizing performance due to logs that lacked detailed SQL query information.This made it difficult to identify specific performance bottlenecks, as the logs only provided general data on database interactions and view rendering times.A recent update to the Rails framework, offers an insightful enhancement to how Rails logs SQL queries during template rendering.This feature is particularly useful for developers who need to monitor SQL queries to optimize performance and debug issues efficiently.BeforePrior to the implementation of this feature, Rails logs displayed basic metrics about the requests processed, including total time, view rendering time, and database interaction time.However, they lacked detailed information about the count and type of SQL queries executed.Let’s take a code snippet to understand the behavior betterdef index @users = User.includes(:products).where.not(products: { id: nil })endThe typical log output for the above code
1ヶ月前
記事のアイキャッチ画像
A Quick Guide to Ruby's Time and DateTime Classes
Saeloun Blog
IntroductionRuby has three main classes for handling date and time: Date, Time, and DateTime.The DateTime class is a subclass of Date and is used to handle date, hour, minute, second, and offset.However, The Ruby documentation also recommends using the Time class instead of DateTime.The DateTime class is still available in Ruby for backward compatibility, but developersare encouraged to use the Time class for new projectsand to migrate existing code to use the Time class.DateTime in RubyDateTime in Ruby is a class that can handle date, hour, minute, second, and offset. It is a subclass of the Date class. The DateTime class can be used to represent a specific point in time with a specified offset from UTC.require 'date'datetime = DateTime.new(2023, 1, 1, 12, 0, 0, '-05:00')# <DateTime: 2023-01-01T12:00:00-05:00 ((2459946j,61200s,0n),-18000s,2299161j)In the above example, we are using the new method, passing in theyear, month, day, hour, minute, second, and offset as arguments.An offset
1ヶ月前
記事のアイキャッチ画像
Rails 8 adds Rubocop by default to new applications
Saeloun Blog
RuboCop is a static code analyzer also linter and code formatter for the Ruby programming language.It will enforce the guidelines outlined in the communityRuby Style Guide.It helps developers in ensuring adherence to coding style standards, identifying potential code flaws,and enhancing the overall quality of the codebase.In addition to identifying code problems, RuboCop also automatically corrects those issues.Developers can adjust rules defined by Rubocop to match project coding standards.Before Rails 8.0Before Rails 8 we had to manually integrate Rubocop gem to our project.We can simply install it like below.gem install rubocopor we can add it to the gemfile of the project.gem 'rubocop', require: falseThe behavior of RuboCop can be controlled via the .rubocop.yml configuration file. We can create this file manually and we can put it in the root of our project folder.Or we can run the below command that will automatically create the rubocop.yml and rubocop.todo.yml file.It is a good
1ヶ月前
記事のアイキャッチ画像
Rails 8 Adds Rate Limiting to Action Controller via Kredis Limiter Type
Saeloun Blog
Let’s understand what is Rate LimitingRate limiting is a technique used to control the rate of incoming requests or traffic to a server,API, or service. It helps in limiting the rate at which requests are processedwhich ensures system security and performance.By restricting the rate of requests made by individual clients or IP addresses, helpsin preventing abuse, such as denial-of-service attacks or brute-force login attempts.Now question is how to do this in Rails.Before Rails 8.0Before Rails 8 there were different ways to implement rate limiting that depends onspecific requirements and constraints.One such way of it is by using rack-attack gem.To use this gem, we need to create a new file config/initializers/rack_attack.rb andthen we can write rate limiting rules in this file.For example, if we want to block access to all admins we can define rules in the following way:# config/initializers/rack_attack.rbRack::Attack.blocklist("block all access to admin") do |request| # Requests are
2ヶ月前