...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
Rails partials have a lot of "hidden" features and this card describes some non-obvious usages of Rails Partials. Rendering a basic partial The most basic way to render a...
...B.end && B.start <= A.end The code below shows how to implement this in Ruby on Rails. The example is a class Interval, which has two attributes #start_date and #end_date...
Starting with Rails 7.1 the production logger is set to standard out. For applications running with opscomplete ensure to keep logging to a file as before (e.g. when running bin/rails...
...be enough to change these lines in the config/environments/production.rb back to the implementation in Rails <7.1: - # Log to STDOUT by default - config.logger = ActiveSupport::Logger.new(STDOUT) - .tap { |logger| logger.formatter = ::Logger::Formatter.new
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
Sometimes you need to remove high Unicode characters from a string, so all characters have a code point between 0...
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...
Rails 7.1 added a new method Rails.env.local?. If you want to stub the Rails env correctly, use ActiveSupport::EnvironmentInquirer like this: # check if the value of stubbed_env is valid...
...allow(Rails).to receive(:env).and_return(ActiveSupport::EnvironmentInquirer.new(stubbed_env.to_s...
tl;dr Prefer request specs over end-to-end tests (Capybara) to joyfully test file downloads! Why? Testing file downloads
...is included in migrations by default (also see How to write complex migrations in Rails). Handy methods Note that both keys and values are always strings, i.e. you'll need...
...I needed to do to add esbuild to an application that used the vanilla rails asset pipeline with sprockets before. Preparations update Sprockets to version 4 add a .nvmrc with...
...your preferred node version (and install it) add gems jsbundling-rails and foreman to your Gemfile: gem 'jsbundling-rails' group :development, :test do gem 'foreman' # ... end bundle install
Normally, Rails handles encryption and signing of cookies, and you don't have to deal with the matter. Should you need to decrypt a session cookie manually: here is how...
...Obviously, you can only decrypt a session cookie from within the corresponding Rails application. Only the Rails application that encrypted a cookie has the secrets to decrypt it.
...response time of a notoriously slow JSON API endpoint that was backed by a Rails application. While every existing app will have different performance bottlenecks and optimizing them is a...
The data flow examined in this card are based on an example barebone rails app, which can be used to reproduce the results. I tried to mimic the case...
...a clever migration, possibly by embedding the model into the migration script. Open the Rails console after deployment and re-save every single record. You should probably add two chores...
It is very common to parse dates from strings. It seems obvious to use Date.parse for this job. However this...
...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 a way to prepend (or append) view paths for the current request. This way, you can make the application use different view templates for just that request.
...action :prepare_views def index # ... end private def prepare_views if prepend_view_path Rails.root.join('app', 'views', 'special') end end end If is true, Rails will first look into app/views/special...
All columns of a model's database table are automagically available through accessors on the Active Record object.
If you are using the routing-filter gem in your Rails 7.1 app for managing URL segments for locales or suffixes, you will notice that the filters do no longer...
...and the necessary parameters are no longer extracted. That is because routing-filter patches Rails' find_routes-method to get the current path and apply its defined filters on it...
...best practices to maintain your tasks in larger projects. Rake Tasks vs. Scripts The Rails default is using rake tasks for your application tasks. These live in lib/tasks/*.
end end Example for a script: The slim ruby script: lib/scripts/user_export.rb: # bundle exec rails runner -e development lib/scripts/user_export.rb Gitlab::UserExport.new.export The main code lib/scripts/gitlab/user_export.rb: module Gitlab class UserExport
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...
Rails is split into a large number of (sub-) frameworks. The most important and central of those are activesupport (extends the Ruby standard library) activerecord / activemodel (ORM for Rails)
...gem 'actionmailer', require: false) as well. When you look into the definition of rails/all (in railites-x.x.x/lib-/rails/all.rb) you can find the exact path for requiring the sub-frameworks.
Development environment setup Rails Composer Basically a comprehensive Rails Template. Prepares your development environment and lets you select web server, template engine, unit and integration testing frameworks and more.
...in minutes using an application template. With all the options you want! Code generators Rails Bricks A command line wizard. Once you get it running, it creates sleek applications.
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