...1M downloads), and geordi (> 200k downloads) Developing a Ruby gem is different from developing Rails applications, with the biggest difference: there is no Rails. This means: no defined structure (neither...

...to require all files yourself no active_support niceties Also, their scopes differ. A Rails application usually combines many libraries with custom code. It runs on a given version of...

...ActiveRecord scope. Depending on what you want to achieve, this is quite easy with Rails 7, and a bit more complicated with Rails 6 and below, or when the inverse...

...to get all users which are not part of User.admins, say: User.where.not(id: User.admins) Rails will generate a query like the following. SELECT * FROM users WHERE id NOT IN (SELECT...

...subject line for each new mailer method. class SubjectPrefixInterceptor def self.delivering_email(message) message.subject = "[#{Rails.env}] #{message.subject}" end end unless Rails.env.production? ActionMailer::Base.register_interceptor(SubjectPrefixInterceptor) end Define it in an initializer...

@allowlists ||= {} @allowlists[environment] ||= Allowlist.new(config.fetch(environment, {})) end private def config @config ||= YAML.load_file(Rails.root.join('config/mail_allowlist.yml')).freeze end end extend ClassMethods end class AllowlistInterceptor def self.delivering_email(message) allowlist = AllowlistConfig.for...

Every modern Rails app should have a Content Security Policy enabled. Very compatible default The following "default" is a minimal policy that should "just work" for almost all applications

...you most of the benefits of a CSP In your config/initializers/content_security_policy.rb, set Rails.application.config.content_security_policy do |policy| policy.object_src :none policy.script_src :unsafe_eval, :strict_dynamic, :https # Browsers with support...

...same pattern applies to any slow external API you want visibility on. Hooking into Rails' controller instrumentation allows us to get additional information like this in every log line:

...Ollama: 11443.1ms (queries: 8, input: 1218, output: 158) | GC: 87.7ms) This extends Rails 7 Server Timings, so the same numbers also show up in the browser's DevTools...

Below is a strict, but still workable Content Security Policy for your Ruby on Rails project. Use this CSP if you want to be very explicit about what scripts you...

...config/initializers/content_security_policy.rb with the code below. Go through each comment and make adjustments where necessary. Rails.application.config.content_security_policy do |policy| # Allow nothing by default policy.default_src :none # Allow fetch and websocket...

To add a few basic styles to the default error pages in Rails, just edit the default templates in public, e.g. public/404.html. A limitation to these default templates...

...is that they're just static files. You cannot use Haml, Rails helpers or your application layout here. If you need Rails to render your error pages, you need the...

...deploys or servers If you save your uploads to a made up directory like "RAILS_ROOT/uploads", this directory goes away after every deploy (since every release gets a new). Also...

Only two folders are, by default, shared between our application servers and deployments: "RAILS_ROOT/storage" and "RAILS_ROOT/public/system" (note that this might be different if you are not hosting...

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...

A Rails script lives in lib/scripts and is run with bin/rails runner lib/scripts/.... They are a simple tool to perform some one-time actions on your Rails application. A Rails...

...script has a few advantages over pasting some prepared code into a Rails console: Version control Part of the repository, so you can build on previous scripts for a similar...

...four variants, that add a more intuitive workflow when working with nested attributes in Rails + Unpoly: Without JS With HTML template and JS With HTML template and JS using dynamic...

guides.rubyonrails.org

...HTML-safe when translating with t('.your_key_html'). When you're localizing a Rails application, some localized texts need to contain HTML. Be it some localized link, or some...

...to learn more about <strong>the corporation</strong>. Alright. Rails is being helpful here and saves you from accidentally injecting HTML into the page. But how...

...inside. You can modify it there, and export it as an image. Option B: Use rails-erd Install rails-erd following the steps in their installation instructions. Run bundle exec...

...diagram, this is cumbersome on large projects, and can't be automated. You can use rails-erd instead. As an example, here is a Rake task where we render only...

Every Rails response has a default ETag header. In theory this would enable caching for multiple requests to the same resource. Unfortunately the default ETags produced by Rails are effectively...

...random, meaning they can never match a future request. Understanding ETags When your Rails app responds with ETag headers, future requests to the same URL can be answered with an...

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly updates work using AJAX requests, you...

...show with full CSS and JavaScript. The code assumes you are using Ruby on Rails with better_errors, which is the default error view that modern Rails versions employ. If...

Rails middlewares are small code pieces that wrap requests to the application. The first middleware gets passed the request, invokes the next, and so on. Finally, the application is invoked...

...can run rake middleware to get the ordered list of used middlewares in a Rails application: $> rake middleware use Webpacker::DevServerProxy use Rack::Sendfile use ActionDispatch::Static use Rack::LiveReload...

...the config.x configuration in combination with config_for to configure global settings for your Rails 4.2+ application. Example In your config/application.rb assign the settings from e.g. config/settings.yml as follows:

class Application < Rails::Application config.x.settings = config_for(:settings) end end The config/settings.yml might look as follows: shared: &shared email: info@example.com google_analytics: container: UA-123456-12 test: <<: *shared

github.com

The new params.expect method in Rails 8 improves parameter filtering, addressing issues with malformed input and enhancing security. It provides a cleaner, more explicit way to enforce the structure and...

...hash or array) is provided for the permitted attributes. Example Basic Usage # Old before Rails 8 user_params = params.require(:user).permit(:name) # New since Rails 8 user_params = params.expect(user...

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.

...with resources as well, e.g. resources :examples, path: 'demonstration' Two macros for namespacing routes Rails offers two macros for namespacing routes. As its name suggests, namespace is the tool for...

Method delegation in Rails can help you to keep your code organized and avoid deep call chains (law of demeter) by forwarding calls from one object to another. Rails provides...

...method_missing(method_name, *args, &block) @user.public_send(method_name, *args, &block) end end Rails shortcut: delegate_missing_to Because this is such a common pattern (e.g. for building something...

...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...

Rails gives you migrations to change your database schema with simple commands like add_column or update. Unfortunately these commands are simply not expressive enough to handle complex cases.

...card outlines three different techniques you can use to describe nontrivial migrations in Rails / ActiveRecord. Note that the techniques below should serve you well for tables with many thousand rows...

If you're suffering from a huge de.yml or similiar file, cry no more. Rails lets you freely organize your dictionary files in config/locales. My organization works like this: config/locales/rails.de.yml...

...modified Rails boilerplate config/locales/faker.de.yml modified Faker boilerplate config/locales/models.de.yml model names, attribute names, assignable_value labels config/locales/views.de.yml text in the GUI config/locales/blocks.de.yml if you organize your CSS with BEM you can...