end html end Full disclosure: Under the hood this uses the private Rails helper method split_paragraphs that simple_format uses. While it might break when upgrading Rails...

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

...BEM, block-by-block. Read Read the chapter "Taming Stylesheets" from our book Growing Rails Applications in Practice (in our library). Talk with a colleague about the reasons for the...

...a good BEM structure in the DOM tree of these websites: https://makandra.de/ https://railslts.com/ https://www.aitiraum.de/ Practice: Cards In a new project, try to layout the style of...

...stack of tools. Start this card by skimming over the linked resource. Discussion Growing Rails applications in practice Read the following chapters from our book Growing Rails Applications in Practice...

...On following fashions Surviving the upgrade pace of Rails Owning your stack Discuss each chapter with your mentor. The Swinging Pendulum The XKCD about the sandboxing cycle is quite on...

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

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

In modern Rails versions you can also use ActiveRecord's pluck method. User.active.pluck(:id) => [1, 5, 23, 42] If you are plucking from the id column in particular you can...

...not the resulting array). Article.distinct.pluck(:state) # SELECT DISTINCT state FROM articles => ['draft', 'published'] In Rails 3 and 4 you must use uniq instead of distinct: Article.uniq.pluck(:state) # SELECT DISTINCT state...

makandra Curriculum

...is rake good for? Take a look at some of the Rake tasks that Rails gives you (rake -T within a Rails project) Find the code that defines the rake...

...stats task in the Rails gems What are some ways how a Rake task can execute another task? What does it mean if a Rake task "depends" on another task...

In Rails, we usually have a mailer setup like this: class MyMailer < ActionMailer::Base def newsletter mail to: 'receiver@host.tld', from: 'sender@host.tld', subject: 'My mail' end end If you want to...

mail = MyMailer.newsletter File.open('my_mail.eml', 'w') { |file| file.write(mail.to_s) } Now, close the rails console and preview the mail: xdg-open my_mail.eml There is not much magic in this...

makandra dev

...app/models/test.rb index eg3c1k1..843c0a2 31143 --- app/models/test.rb +++ app/models/test.rb @@ -19,6 +19,10 @@ module RoutingFilter path = Rails.root / 'app' + if true + + end + return path (1/1) Discard this hunk from worktree [y,n,q...

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

...your application perform with lots of data? Generate many records per table. Watch the Rails logs and query_diet to find areas of improvement. Reduce N+1 queries, preload associations...

...for every little thing. Jasmine is a purely client-side tool. It cannot ask Rails to render a view or access the database. Any HTTP calls must be mocked.

Tip Create the required DOM directly from your Jasmine spec. You cannot ask Rails to render a view. You can use Element#dispatchEvent() to emit events on a DOM...

github.com

RSpec.configure do |config| config.include Aegis::Matchers end In very old versions of Rails and RSpec you need to do this instead: ActiveSupport::TestCase.send :include, Aegis::Matchers

...check Nokogiri::VersionInfo.instance.warnings for any warnings (though they should appear e.g. when launching a Rails console) or Nokogiri::VersionInfo.instance.to_hash to view more information. Note If your application uses Spring...

makandra dev

While most Rails Apps are tied to at least one external REST API, machine-to-machine communication via GraphQL is less commonly seen. In this card, I'd like to...

...w[errors]) unless response.status.ok? parsed_response end def client headers = { 'Content-Type' => 'application/json', 'Authorization' => Rails.application.secrets.fetch(:linear_api_key), } HTTP.headers(headers) end end Writing data (Mutation) Performing GraphQL mutations is equally...

etag { current_user&.id } etag { current_user&.updated_at } end Under the hood, Rails generates an ETag header value like W/"f14ce3710a2a3187802cadc7e0c8ea99". In doing so, all objects from that...

...etag { current_user&.updated_at&.to_f } end You might even want to patch Rails' etagging logic so you don't have to remember doing that. Here you go:

...you're not familiar with the pattern, read or re-read "New rules for Rails" from Growing Rails Applications in Practice (in our library) How to navigate between indexes, show...

docs.ruby-lang.org

...without changing the return value: def save_user user.save.tap do |saved| next unless saved Rails.log("User was created, we have #{user.count} users now!") end end save_user # User was created...

...in webpack.config.js: { ... optimization: { minimize: true, minimizer: [ new TerserPlugin({ terserOptions: { ..., mangle: { properties: { regex: /^[_#]/ } } } }) ] } } Configuring Webpacker (Rails) To configure Webpack to mangle private properties, make a change to your Terser configuration in...

.sort_by(&:last) .to_h end end Just paste that snippet into a Rails console and use #count_by now! Usage examples Number of email addresses by domain: > User.all.count...

...Article.all.count_by &:brand Note that the last simple example can also be achieved with Rails internals: Article.group(:brand).count. This translates to SQL, so it executes fast. However, grouping is...

...like above: new(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout') Difference between Rails mailer and ERB Rails mailer <% if true %> <%= 'bar' %> <% end %> <%= 'foo' %> <%= 'bar' %> bar foo bar

...users.map { |user| [user.id, user.name] }.to_h { 1 => "Alice", 2 => "Bob" } Enumerable#index_by (any Rails version) users = User.all users_by_id = users.index_by(&:id) { 1 => #<User id: 1, name: "Alice...

...User id: 1, name: "Alice">], "Bob" => [#<User id: 2, name: "Bob">] } Enumerable#index_with (Rails 6+) To generate a hash where array elements become hash keys, and values are calculated...