💎Ruby tip💎
Did you know that concatenating strings together ("a" << "b") is a lot more performant than adding them to each other ("a" "b") or using interpolation ("#{a}#{b}")?
Especially with the recent optimizations from @_byroot and others.
#ruby#rails#rubyonrails
💎Ruby tip💎
Did you know that Ruby gives you a powerful string formatter to do things like choosing the number of decimals, converting to binary, octal, hexadecimal, and a lot more?
Examples ⬇️
#ruby#rails#rubyonrails
ALT # Make a number always show 2 decimals (useful for money)
"%.2f" % 10 # => "10.00"
"%.2f" % 10.50 # => "10.50"
# You can even add the currency sign
"$%.2f" % 10.50 # => "$10.50"
# Convert to hexadecimal
"%#x" % 1234 # => "0x4d2"
# And it can do a lot more!
# % is a shortcut that uses Kernel#sprintf behind the scenes
# so if you're looking for the format specification, check
# out the official ruby doc for Kern...
💎Rails tip💎
Did you know you could speed up your dev environment a bit by clearing up logs and temporary files? Especially when it's been a long time since it hasn't been cleared.
#ruby#rails#rubyonrails
ALT rails tmp:clear
rails log:clear
# shortcut for both at the same time
rails tmp:clear log:clear
# keep in mind that this is irreversible so do this
# only if you don't mind losing your logs or tmp files
After building and testing a long time RubyCompanion, it's finally open to everyone! 🎉
We are still actively working on it and more content will be coming too!
rubycompanion.dev/
💎Rails tip💎
Did you know about the view helper "capture"? It allows you to store HTML into a variable and pass it down somewhere else. You don't necessarily need view_component slots to do that!
#ruby#rails#rubyonrails
ALT <% body = capture do %>
<div>
The body of the modal goes here!
<%= link_to "Confirm", "#" %>
</div>
<% end %>
<%= render "shared/modal", body: body %>
# shared/_modal.html.erb
<div>
<div>Header</div>
<div><%= body %></div>
<div>Fooder</div>
</div
💎Ruby tip💎
Did you know that you can use the ampersand(&) operator with any method that
require a block for some convenient shortcuts?
Examples ⬇️
#ruby#rails#rubyonrails
ALT array = [nil, "", 2]
# To convert all values to strings
# instead of
array.map { |value| value.to_s }
# you can do
array.map(&:to_s)
# => ["", "", 2]
# Or to remove any nil or empty values
array.find_all(&:present?)
# => [2]
# The trick is that the ampersand(&)
# operator will convert to a proc
# and give it as a block. Converting
# a symbol to a proc will call the
# method on the param.
:to_s.to_proc.call(1)
# ...
💎Rails tip💎
Did you know about template variants? Useful when you have let's say one view for admins and one for normal users. Or one for mobile and one for desktop (when the views are too different to just be responsive).
#ruby#rails#rubyonrails
ALT class DashboardsController < ApplicationController
def show
request.variant = Current.user.admin? ? :admin : :user
end
end
# View path if admin:
# app/views/dashboards/show.html admin.erb
# View path if normal user:
# app/views/dashboards/show.html user.erb
💎Rails tip💎
Did you know Rails 7 added support for PostgreSQL generated columns? These columns will be calculated by the database only once on INSERT and UPDATE.
#ruby#rails#rubyonrails
ALT # db/migrate/20220226153929_create_orders.rb
class CreateOrders < ActiveRecord::Migration[7.0]
def change
create_table :orders do |t|
t.integer :subtotal_cents
t.integer :tax_cents
t.virtual :total_cents, type: :integer, as: "subtotal_cents tax_cents", stored: true
t.timestamps
end
end
end
# console
Order.create(subtotal_cents: 1000, tax_cents: 200)
Order.last.total_ce...
💎Rails tip💎
Did you know that Rails 7 added a way to run queries in parallel? This can give good performance gains if you have multiple queries in a single controller action. Example below ⬇️
#ruby#rails#rubyonrails
ALT # config/application.rb
config.active_record.async_query_executor = :global_thread_pool
# :multi_thread_pool executor can be used if you have multiple databases
# app/controllers/dashboards_controller.rb
class DashboardsController < ApplicationController
def show
# These queries will all run asynchronously
# instead of running one by one
@posts = Post.limit(500).load_async
@users = User.limit(50...
As someone just told me, when running this on MRI, the term is "concurrently", not "in parallel". Because GIL prevents parallel code execution. But the result, time-wise, should be about the same!
💎Rails tip💎
Did you know that since Rails 6.1, you can easily add a column of type interval if you use Postgres? This can be convenient if you have for example a model for recurring events with a specific duration like 5 days.
#ruby#rails#rubyonrails
ALT class CreateEvents < ActiveRecord::Migration[6.1]
def change
create_table :events do |t|
t.string :name
t.interval :duration
t.timestamps
end
end
end