...That's not supported by our version managers like mise. Testing compatibility in a Rails project In general, a recent Rails projects should use the currently active LTS version of...
...module structure. The typical example would be the concerns folder, which exists in new Rails applications by default and does not create a constant module Concerns. app ├── models ├── concerns ├── shareable.rb...
...following official api: app ├── models ├── shared ├── shareable.rb # Defines constant Shared::Shareable # e.g. in application.rb Rails.autoloaders.main.collapse("#{Rails.root}/app/models/shared") # with collapsed shared dir app ├── models ├── shared ├── shareable.rb # Defines constant Shareable
Add gem 'database_cleaner' to your Gemfile. Then: Cucumber & Rails 3+ # features/support/database_cleaner.rb DatabaseCleaner.clean_with(:deletion) # clean once, now DatabaseCleaner.strategy = :transaction Cucumber::Rails::Database.javascript_strategy = :deletion Cucumber & Rails 2
...available cucumber-rails for Rails 2 automatically uses database_cleaner when cucumber/rails/active_record is required -- but only if transactional fixtures are off. To have database_cleaner work correctly: Add the attached...
...table that is missing them. You can use the add_timestamps macros for that. Rails >= 4.2 Since Rails 4.2 add_timestamps also adds a NOT NULL constraint by default. So...
...SET updated_at = '#{time}'" # Restore NOT NULL constraints to be in line with the Rails default change_column_null :shows, :created_at, false change_column_null :shows, :updated_at, false...
...find out which parts of your application are not tested. Integrating this in a rails project with rspec, cucumber and parallel_tests is easy. Add it to your Gemfile and...
...gem 'simplecov', require: false end Add a .simplecov file in your project root: SimpleCov.start 'rails' do # any custom configs like groups and filters can be here at a central place...
...to set the default_url_options of ActionMailer: Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs) Dynamic solution 1. Hardcoded solution When you are sending mails from...
...e.g. ActiveJob/Sidekiq or Cronjobs, you need to configure the default_url_options in your Rails configuration. # config/application.rb as fallback/default Rails.application.default_url_options = { host: 'localhost', port: 3000, protocol: 'http://' } Rails.application.configure do...
Rails has generic error messages you can define in your locale .yml files. You may override those application-wide error messages using model or attribute scope like this: en: activerecord...
This card will teach you how to index, search and rank your Rails models in a PostgreSQL full-text index. We will do this without using any gems...
...Basics and Previews Chapter "Task H1: Sending Confirmation Emails" from Agile Web Development with Rails (in our library) Ensure that the receiving e-mail is valid Using the Truemail gem...
Ensure that development and staging are not sending out e-mails by accident Rails: How to write custom email interceptors Check if you have a local mail server listening...
...rolls back the transaction, nothing will be saved. The user will probably see a Rails error box. Improving the user experience In 99% of all cases adding a uniqueness key...
...is guaranteed. There are however cases where you want to improve the user behavior (Rails error box) or reduce the number of exceptions e-mailed to your / collected by your...
...from various browser extensions of your visitors. Add the endpoint in you CSP config/initializers/content_security_policy.rb: Rails.application.configure do config.content_security_policy do |policy| # Settings for the policy policy.report_uri '/content_security_policy_report' end
class ContentSecurityPolicyReportsController < ApplicationController skip_forgery_protection def create if request.content_type == 'application/csp-report' Rails.logger.info("Content Security Policy Report: #{request.user_agent} #{request.body.read}") head :ok else head :bad_request end
Debugging performance issues in your Rails app can be a tough challenge. To get more detailed insights consider using the rack-mini-profiler gem. Setup with Unpoly Add the following...
...up.link.config.noFollowSelectors.push('.profiler-results a') document.addEventListener('up:link:follow', () => { if (window.MiniProfiler !== undefined) { window.MiniProfiler.pageTransition() } }) } # config/initializers/rack_mini_profiler.rb if Rails.env.development? Rails.application.config.to_prepare do Rack::MiniProfiler.config.position = 'top-right' # positon widget top-right Rack::MiniProfiler.config.skip_paths = [ # ignore...
Rails is our web framework. Goals Be able to write a simple Rails application. Understand how Rails talks to the database (ActiveRecord) What is a model? How are records retrieved...
...has_many, has_many :through Gain an understanding of the structure of a basic Rails app Routes Controllers Generate a controller using Rails scaffolding Write your own controller Views
Rails supports time zones, but there are several pitfalls. Most importantly because Time.now and Time.current are completely different things and code from gems might use one or the other.
...only about one time zone is a bit tricky. The following was tested on Rails 5.1 but should apply to Rails 4.2 as well. Using only local time
...See this ES6 compatibility matrix for details. ES6 and Uglifier If you're using Rails with the assets pipeline (sprockets) you are probably using Uglifier to minify your JavaScript.
...can check if that's an issue for your project by running bundle exec rails assets:precompile in your development environment (don't forget to run bundle exec assets:clobber...
...a few minor exceptions for our Austrian friends. Luckily, the I18n gem used by Rails has a fallback feature where you can make one locale file fall back to another...
... and another locale config/locales/de_AT.yml: de_AT: # only a handful exceptions here Now configure Rails to make de_AT fall back to de_DE: Rails.application.configure do config.i18n.fallbacks = { de_AT: :de...
...written as a Ruby Gem and was tested and evaluated against one Ruby on Rails project. This card will summarize and present the research results, the evaluation and the programmed...
...The tool should be suitable for modern web based development workflows with Ruby on Rails. Criteria Faster results of failing tests than random prioritization to lower regression testing costs.
Rails offers the fresh_when method to automatically compute an ETag from the given record, array of records or scope of records: class UsersController < ApplicationController def show @user = User.find(params...
In Rails, the implicit_order_column (added in Rails 6) is a configuration option that helps you define the default sorting behavior of ActiveRecord queries when no explicit ORDER BY...
...clause is provided. This option allows you to specify a column that Rails will use to automatically sort records in a particular order when no specific ordering is given.
Rails includes a way to see what an e-mail will look like. Integration to RSpec All you need to do is implement a preview-class in spec/mailers/previews/notifier_preview.rb: class NotifierPreview...
end end And adapt the preview load path in your application.rb: config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews" # For Rails < 7.1 config.action_mailer.preview_paths << "#{Rails.root}/spec/mailers/previews" # For Rails >= 7.1 Then a preview will...
...an empty exclusion list returns no records at all! See below for better implementations. Rails 4+ Use the .not method to let Rails do the logic # Good User.where.not(id: []).to...
=> SELECT "users".* FROM "users" WHERE "users"."id" NOT IN (1, 2) Rails < 4 Before Rails 4, you needed to work around this yourself: # Good excluded_ids.blank? ? User.all : User.where("id...
Why Rails has multiple schema formats When you run migrations, Rails will write your current database schema into db/schema.rb. This file allows to reset the database schema without running migrations...
...by running rails db:schema:load. The schema.rb DSL can serialize most common schema properties like tables, columns or indexes. It cannot serialize more advanced database features, like views, procedures...
Rails wraps your parameters into an interface called StrongParameters. In most cases, your form submits your data in a nested structure which goes hand in hand with the strong parameters...
...expect/permit/require when passing them to e.g. ActiveRecord. Note that expect is only available from Rails 8. There are cases where it might be fine to read directly, like: # Okay
TL;DR: Rails ships two methods to convert strings to constants, constantize and safe_constantize. Neither is safe for untrusted user input. Before you call either method you must validate...
...w[User Post Test]) if class_name class_name.safe_constantize.new # either User, Post or Test else Rails.logger.error "This should not happen!" end Handling unresolvable constants The safe_constantize method is defined in...