makandra dev
github.com

...note that some of the functions edge_rider provides have native implementations in newer rails versions. Useful in applications Relation#traverse_association(*names) Edge Rider gives your relations a method...

...These utilities are mostly useful in libraries that need to support multiple versions of Rails. They offer a unified interface across Rails versions. Relation#collect_ids You should not use...

...worldwide by developers looking for help and tips on web development with Ruby on Rails and DevOps. 15 years ago – in 2009 – we wrote our first card. Since then, over...

...in makandra cards We gain the most experience in web development and Ruby on Rails in our day-to-day work, as web development is our largest team and we...

...you have a maintenance script where you want to iterate over all ActiveRecord models. Rails provides this out of the box: # script/maintenance_task.rb # Load all models eagerly, otherwise you might only...

Rails.application.eager_load! ApplicationRecord.descendants.select(&:table_exists?).each do |model| # ... end Caution If you iterate over individual records, please provide a progress indicator: See https://makandracards.com/makandra/625369-upload-run-scripts-production Caution

...Using unguessable URLs. This is fast (because Apache can deliver assets without going through Rails), but less secure. When going with the "unguessable URL" approach, it is possible to somewhat...

...with SecureRandom.hex(32), and also put it as url_signature_secret into your secrets.yml. Rails helper To generate an expiring URL, use the following helper: def sign_public_path(path...

Rails offers several methods to manage three types of different cookies along with a session storage for cookies. These are normal, signed and encrypted cookies. By following the happy...

...sparse and only focuses on controller specs, which recommended usage have been limited since Rails 5+ (see "Rails: Support for Rails 5"), this card will summarize some guidance on how...

Background information about session storage in Rails Rails has a default mechanism to store the session in the CookieStore. This is a cookie which holds the entire user session hash...

...changelog_path = File.expand_path('../CHANGELOG.md', __dir__) Ruby < 2.0 changelog_path = File.expand_path('../../CHANGELOG.md', __FILE__) Rails changelog_path = Rails.root.join('CHANGELOG.md...

makandra dev

...query -> query embedding -> kNN search -> ranked pages | +--------------------------------------------------------------------+ See: How to add RAG to your Rails application Full-text keyword search (BM25) Full-text search splits each document into tokens (words...

...calls in local and CI tests. See also How to add RAG to your Rails application: vector search end-to-end. You don't need a vector database to build...

...accidentally translates the query. It might be a good idea to cache the result (Rails.cache) for some time so a page reload doesn't re-call the LLM. Authorize the...

...to Hybrid search for the trade-offs, or How to add RAG to your Rails application to get started on the vector branch...

...few examples, where you configure some library via a block. One example is the Rails configuration: Rails.application.configure do |config| config.enable_reloading = false end This card describes a simple example on...

...You can use ActiveSupport::Configurable instead of the Configuration class. When you are using Rails with Zeitwerk and the code for e.g. FooClient lives in a folder, that is loaded...

When deploying a Rails application that is using Webpacker and Capistrano, there are a few configuration tweaks that optimize the experience. Using capistrano-rails capistrano-rails is a Gem that...

...adds Rails specifics to Capistrano, i.e. support for Bundler, assets, and migrations. While it is designed for Asset Pipeline (Sprockets) assets, it can easily be configured for Webpacker. This brings...

You don't want sensitive user data in your logs. Background Rails per default filters sensitive data like passwords and tokens and writes [FILTERED] to the logs. The...

...code which is responsible for enabling that usually lives in filter_parameter_logging.rb (Rails.application.config.filter_parameters). Here is an example of a filtered log entry: Unfiltered: `User Load (0.4ms) SELECT "users".* FROM...

...you UTC objects whose to_s(:db) may not convert properly. Legacy behavior in Rails 2.3 It's been briefly mentioned in the random list of ActiveSupport goodies, but please...

...remember to always use Time.current instead of Time.now, etc. Why? Because of the way Rails and MySQL deal with time zones you would need to take care to use Time.zone.now...

...up repetitive expectations in your specs. Unfortunately the default directory structure generated by rspec-rails has no obvious place to put custom matchers or other support code. I recommend storing...

...to all specs, put the following into your spec_helper.rb, above the RSpec.configure block: Dir[Rails.root.join("spec/support/**/*.rb")].sort.each {|f| require f} Also see where to put shared example groups...

...already shipping as custom elements For example Trix from Basecamp (integrated as ActionText in Rails 6). By choosing custom elements as their delivery method, they work in all JavaScript frameworks...

...alotting time. This is a refactoring similar to removing resource_controller (but not a Rails upgrade). Grep for $. This will show you all the affected lines of code. Refactor functions...

...the same object. You also know that you can reload an association to make Rails load its data from the database again. user.posts.reload # discards cache and reloads and returns user.posts...

...reset returns the association/scope. Hence, the above will not seem to work on the Rails console, just because the return value is inspected and thus resolved right away.

By default, Rails' validates_uniqueness_of does not consider "username" and "USERNAME" to be a collision. If you use MySQL this will lead to issues, since string comparisons are case...

...may fail with an SQL error due to duplicate index key. You can change Rails' behaviour, by saying class User < ActiveRecord::Base validates_uniqueness_of :name, case_sensitive: false

options: { search: 'window.toString() === \'[object GjsGlobal]\'', replace: 'window.toString() === \'[object Window]\'' } }] }) Fix for ESBuild / jsbundling-rails Add the package esbuild-plugin-text-replace to your package.json. Now add the following plugin...

if 'foo' =~ /foo/ puts $LAST_MATCH_INFO[1] # => foo end Require pitfall in Rails The English library is not loaded by default in Rails. So you or another library...

makandra dev

...point over a separate ClassMethods module inside of your module. If you are using Rails (or only ActiveSupport), you may also use ActiveSupport::Concern which facilitates this for you.

...taken in chronological order, you get this: Singleton class Class Included modules Superclass(es) Rails 5 introduced prepended modules which allow you to patch methods in a class in a...

github.com

Zeitwerk is the new autoloader of Rails. It is mandatory starting with Rails 7.0. Sometimes, a model needs to know all its descendants. They might be organized in a subdirectory...

...needs to iterate all design subclasses. To eager load all designs, use this line: Rails.autoloaders.main.eager_load_dir(Rails.root.join 'app/models/design') Make sure that app/models/design.rb is not required manually before instructing Rails...

Rails Active Support provides some helpful methods for calculating times and dates, like Duration#ago or Duration#from_now. But beware when using those, because they wont give...

...timezone unaware. Moreover, you have to be aware that ActiveSupport::TimeWithZone does not use Rails.application.config.active_record.default_timezone, which you need to define, even if you only use your local timezone, but...

makandra dev

# Redis db#1 is used for development. db_number = 1 if rails_env == 'test' normalized_test_number = [ENV['TEST_ENV_NUMBER'].to_i, 1].max db_number += normalized...

end db_number end def port case rails_env when 'staging' # when 'production' # else 6379 # default Redis port end end def rails_env defined?(Rails) ? Rails.env : ENV['RAILS...

Running rails server will start a local server that you can access via http://localhost:3000. When you are working on multiple web apps, they will likely set cookies with...

...define it in a single place so switching it out will be easy. Modern rails versions will block hosts other than localhost by default. Therefore create an entry in config/environments/development.rb...