Ruby on Rails - Oct 2024
Sajjad Umar
Senior Backend Engineer | Ruby on Rails | Manager RubyConf. Pakistan | Author of Ruby on Rails for Agile Web Development | Desi Developer | Building adex.world
The only Ruby on Rails newsletter you will ever need!?
Hey Ruby folks?—?this is a fascinating month for the Ruby on Rails community as RailsWorld has been concluded and we have a lot of exciting updates to share.?
Let’s Jump right in!?
Rails World 2024 Opening Keynote?—?David Heinemeier Hansson
During DHH’s Opening Keynote of Rails World 2024 in Toronto, Rails 8 beta was shipped with Authentication, Propshaft, Solid Cache, Solid Queue, Solid Cable, Kamal 2, and Thruster. No PaaS is needed when building with the One Person Framework.
Watch the Keynote session here:
Rails 8 is?here!?
Rails 8.0 Beta 1 is live and here are all the highlights from Rails 8 beta 1.
Despite being a beta release, the vast majority of everything that’s included has already been thoroughly battle-tested. Rails is uniquely blessed to have huge applications like Shopify and GitHub, along with plenty of other apps of all sizes, run right on the bleeding edge of the framework to ensure that issues are caught early.
Furthermore, all the new deployment tools, as well as Solid Cache and Solid Queue, have been driving the cloud exit at 37signals for over 18 months in applications like Basecamp and HEY.
Ruby on Rails for Agile Web Development?
Thank you for all the support and positive feedback on my first book titled “Ruby on Rails for Agile Web Development”.?
Ruby on Rails for Agile Web Development: A Hands-on Guide to Building Dynamic and Efficient Web… Ruby on Rails for Agile Web Development: A Hands-on Guide to Building Dynamic and Efficient Web Applications (English… a.co
Get your copy now and keep the feedback coming??
Enter Kamal 2 +?Thruster
Rails 8 comes preconfigured with Kamal 2 for deploying your application anywhere.
Kamal takes a fresh Linux box and turns it into an application or accessory server with just a single “kamal setup” command.
Kamal can do this so easily because Rails already comes with a highly efficient and tuned Dockerfile for turning your application into a production-ready container image out of the box.
In Rails 8, this Dockerfile has been upgraded to include a new proxy called Thruster, which sits in front of the Puma web server to provide X-Sendfile acceleration, asset caching, and asset compression. This means there’s no need to put an Nginx or any other web server in front. The default Rails container is ready to accept traffic from the internet immediately.
Read all about Kamal 2.0 here.
Read all about Thrusters here.
A Solid Reduction of Dependencies
Part of making Rails easier to deploy is to cut down on the number of accessory services required to get going. In the past, Rails needed either MySQL or PostgreSQL as well as Redis to take full advantage of all its features, like jobs, caching, and WebSockets. Now all of it can be done with SQLite thanks to a trifecta of new database-backed adapters named Solid Cable, Solid Cache, and Solid Queue.
Solid Cable
Solid Cable replaces the need for Redis to act as the pub-sub server to relay WebSocket messages from the application to clients connected to different processes. It uses fast polling, but it’s still almost as quick as Redis when run through the same server on SQLite. Beyond plenty fast enough for most applications. As a bonus, Solid Cable retains the messages sent in the database for a day by default, which may ease the debugging of tricky live update issues.
Read more about Sold Cable here.
Solid Cache
Solid Cache replaces the need for either Redis or Memcached for storing HTML fragment caches in particular. In addition to getting rid of the accessory service dependency, it also always for a vastly larger and cheaper cache thanks to its use of disk storage rather than RAM storage. This means your cache can live longer and cover even more requests out the plank of the 95th or 99th percentile. Additionally, this cache can be encrypted and managed by an explicit retention limit (like 30 or 60 days). Making it easier to live up to modern privacy policies and expectations.
Solid Cache has been in production at Basecamp for well over a year where it stores 10 terabytes of data, enables a full 60-day retention window, and cut the P95 render times in half after it’s introduction.?
Read more about Solid Cache here.
Solid Queue
Solid Queue replaces the need for not just Redis, but also a separate job-running framework, like Resque, Delayed Job, or Sidekiq, for most people. For high-performance installations, it’s built on the new FOR UPDATE SKIP LOCKED mechanism first introduced in PostgreSQL 9.5, but now also available in MySQL 8.0 and beyond.?
Solid Queue has been meticulously developed within the pressures of a real production environment over the last 18 months, and today it’s running 20 million jobs per day for HEY alone at 37signals.
Read all about Solid Queue here.
SQLite is ready for production
On top of the trifecta of Solid adapters that make it possible for SQLite to power Action Cable, Rails.cache, and Active Job, a bunch of work has gone into making the SQLite adapter and Ruby driver suitable for real production use in Rails 8.
Some of the PRs for SQLite improvements are here. ?
Replacing Sprockets with Propshaft
Rails 8 makes Propshaft the new default asset pipeline.?
As the new asset pipeline, it replaces the old Sprockets system, which hails from all the way back in 2009.
We thank Sprockets for 15 years of service, but the future of the asset pipeline in Rails is called Propshaft. And it’s now the default for all Rails 8 applications, though we’ll continue to support Sprockets for existing applications.
Read all about Propshaft here.
Authentication Basics
Rails has been assembling high-level abstractions for the key components of an excellent authentication system for a long time.
We’ve had has_secure_password since Rails 5, but also recently introduced generates_token_for?:password_reset along with authenticate_by in Rails 7.1.
Now, Rails 8 is putting all the pieces together in a complete authentication system generator, which creates an excellent starting point for a session-based, password-resettable, metadata-tracking authentication system.
Read all the details about Rails 8 beta 1 here.
Aaron Patterson?—?Rails World 2024 Closing?Keynote
Rails Core member Aaron Patterson delivered the closing keynote at this year’s RailsWorld, which was about speeding up the Rails Router. With his unique blend of humor and presentation style (a little bit technical, a lot of tomfoolery) he also introduced a new feature that may or may not* be in Rails 8: LamboRoutes.
Watch the keynote here:
Eileen Uchitelle?—?The Myth of the Modular?Monolith?
I loved this talk! especially the part where we need to educate the Rails way to new hires and the leadership.
As Rails applications grow over time, organizations ask themselves: ‘What’s next? Should we stay the course with a monolith or migrate to microservices?’ At Shopify, they chose to modularize their monolith, but after 6 years they are asking: ‘Did we fix what we set out to fix? Is this better than before?’?
Join Rails Core member Eileen Uchitelle as she poses these questions during her RailsWorld Day 2 Opening Keynote.
Fireside Chat with DHH, Matz and Tobias?Lütke
In a special RailsWorld session, DHH (creator of Rails), Matz (creator of Ruby), and Shopify CEO Tobias Lütke sat down for a fireside chat about Ruby, Rails, and all things open source.
This is the first time that Matz and DHH shared a stage, and it would not have been possible without Tobi, who not only donated his keynote spot to make this session happen but also led the discussion.
Watch the rest of the sessions on the official Ruby on Rails YouTube channel .?
Refreshed Active Record Validations
This Pull Request has been created to update the Validation docs. PR is open for review.
Read all the details here.
Added ability to use multiple rate limits per controller
Currently, when the controller has multiple rate limits it is not working as expected. It is expected that each rate limit applies only to the actions specified in the?:only, but since the cache key contains the controller path, the rate-limiting cache key is shared between the rate limits. So sending a request to one action we actually increment the rate-limiting counter for other rate limits too.
This PR fixes the issue. Read all the details here.
Added Parameters#expect to safely filter and require?params
This PR adds a new method on ActionController::Parameters that safely handles params filtering in one method, cuts down on ignorable errors caused by params tampering, and improves the specificity of param types.
# Before
params.require(:table).permit(:attr)
# After
params.expect(table: [ :attr ])
Read all the details here.
Thread pool for ActionController::Live
Currently, all controllers that use ActionController::Live create a new thread to process every request. Creating threads is somewhat expensive. We can avoid that by using a thread pool, which we do already elsewhere in Rails.
This PR introduces ActionController::Live.live_thread_pool_executor, which can contain any number of threads, keeping them around for a while (60s is the default in concurrent-ruby).
Read all the details here.
Allowed drop_table to accept an array of table?names
This Pull Request adds support to multiple tables on drop_table on ActiveRecord.
This will ensure that the caching is also cleared which doesn’t happen if you do manually like this:
领英推荐
ActiveRecord::Base.connection.execute 'DROP TABLE a, b, c'
Read all the details here.
Fixed: Set attributes_for_inspect to?:all in the?console
In Rails 7.2, ActiveRecord::Core#inspect was made configurable but people noticed that the console in production was not showing any attributes. This PR sets the default to the previous behavior that was expected.
Read all the details here.
Added if_not_exists option to add_enum_value
This PR Adds support to use the PostgreSQL option IF NOT EXISTS when adding enum values via add_enum_value.
Read all the details here.
Updated Markup and Styles of the error?pages
A refreshed look for error pages is here.
Read all the details here.
Dropped support to Ruby?3.1
Rails 8 will require Ruby 3.2.0 or newer.
Read all the details here.
Added TaggedLogging#logger constructor for a more pleasant logging interface
DHH says “No need to expose such crude welding in a configuration file”.
This PR updates the default logger in production to use ActiveSupport::TaggedLogging.logger(STDOUT).
Read all the details here.
Reverted changes to delegated_type
Automatically inferring?:inverse_of is incompatible with records that do not declare inverse associations.
This PR reverts the changes to delegated_type for the sake of the impending release.
Read all the details here.
Removed require_* statements from application.css
This Pull Request changes the template of the application.css file so that it does not include require_tree and require_self clauses.
Read all the details here.
Set error code to 1 if generator could not be?found
Running rails g in shell scripts should fail in case a generator name is mistyped.
This Pull Request changes the error case when generators are invoked.
# Before
bin/rails generate does_not_exist
echo $?
0
# After
bin/rails generate does_not_exist
echo $?
1
Read all the details here.
Made ActiveModel::Serialization#read_attribute_for_serialization public
Despite the #read_attribute_for_serialization method being declared as private, the module-level ActiveModel::Serialization documentation mentions it explicitly by name.
Mentioning the method directly and encouraging classes to override it to customize behavior breaks Rails existing public-private interface convention.
This commit promotes the method to public visibility.
Read all the details here.
Made ActionController::AllowBrowser::BrowserBlocker private
To reduce the API surface area of the allow_browser feature, this commit marks the class with a #?:nodoc: comment, making it a private API.?
Read all the details here.
Raise an error when invalid?:only or?:except options are given to #resource or #resources
This PR changes the routing helper to raise an ArgumentError when a ActionDispatch::Routing::Mapper::Resources::Resource is initialized with?:only or?:except options that aren’t default (index, create, new, show, update, and destroy) actions.
Read all the details here.
Allowed ActiveRecord::QueryMethods#pluck to accept hash args with symbol & string?values
This PR updates ActiveRecord::QueryMethods#arel_columns_from_hash which is used by #pluck to simply return the Arel attribute for the column by default if the hash value is a symbol or string, while maintaining #select specific aliasing functionality.
Read all the details here.
Made Float distinguish between float4 and float8 in PostgreSQL
This Pull Request fixes the issue when dumping a PostgreSQL schema that includes a float4 column (defined as float(24)), the column is represented as float in the generated schema dump. However, when loading this schema, the float4 column is converted to float8.
Read all the details here.
Fixed ActiveSupport::HashWithIndifferentAccess#stringify_keys to stringify all keys not just?symbols
This pull request changes ActiveSupport::HashWithIndifferentAccess#stringify_keysto stringify all keys, not just symbols.
Before the change:
{ 1 => 2 }.with_indifferent_access.stringify_keys[1] # => 2
After this change:
{ 1 => 2 }.with_indifferent_access.stringify_keys["1"] # => 2
Read all the details here.
Fixed: Incorrect joins for polymorphic has_many through: with association scope
This PR updates ActiveRecord::Reflection::PolymorphicReflection#join_scopes to not apply the previous reflection’s join scopes if it’s a through reflection, as the scope will eventually be built in the context of the polymorphic reflection.
Read all the details here.
Allowed to autosave associations with polymorphic has many through join model and inverse?of
Before this PR following was not possible:
class Zine < ActiveRecord::Base
has_many :interests, inverse_of: :zine
has_many :humans, through: :interests, source: :interestable, source_type: 'Human'
end
class Interest < ActiveRecord::Base
belongs_to :zine, inverse_of: :interests
belongs_to :interestable, polymorphic: true, inverse_of: :interests
end
class Human < ActiveRecord::Base
has_many :interests, as: :interestable, inverse_of: :interestable
end
zine = Zine.create!
zine.humans.create!
# => ArgumentError: Polymorphic associations do not support computing the class.
Now the code checks whether the association is polymorphic and uses the correct code to get the inverse association.
Read all the details here.
Allowed ActiveRecord’s #insert to work with an empty hash of attributes when using?MySQL
Here’s what happens: when calling Book.insert({}), the following exception is raised:
/Users/sto/.gem/ruby/ruby-3.3.5/gems/irb-1.14.1/lib/irb.rb:1260:in
`full_message': Trilogy::ProtocolError: 1054: Unknown column '' in
'field list' (ActiveRecord::StatementInvalid)
This is due to Rails generating the following SQL query:
INSERT INTO `posts` (`created_at`,`updated_at`) VALUES (CURRENT_TIMESTAMP(6), CURRENT_TIMESTAMP(6)) AS `posts_values` ON DUPLICATE KEY UPDATE ``=`posts_values`.`` /*application='MysqlDefaultTime'*/
This simple commit allows it to work.
Read all the details here.
Updated Rails Error Reporting Guide
This PR updates the Rails Error Reporting guide.
Read all the details here.
Stopped executing i18n watcher on?boot
This Pull Request changes Active Support’s I18n railtie to not execute initially. The logic inside of it only applies if files within its watched paths have been added or deleted. I don’t see that happening in any app under normal circumstances.
Read all the details here.
AllowBrowser: support method names for?:block
Prior to this commit?:block options only supported callables. This commit aims to bring browser blocking closer in parity to callbacks declarations like before_action and after_action by supporting instance method names as well.
Read all the details here.
Added?:except_on option for validations
This PR grants the ability to skip Active Model validations in specified contexts.
Read all the details here.
And that is all for this edition of Ruby on Rails Monthly. Keep supporting this newsletter.?
Until we meet again ??
I am a Professional WordPress, PHP, HTML5, CSS3 and BOOTSTRAP4 Website Developer with experience of about 5 years.
1 个月Great advice