Chrome DevTools: DOM Breakpoints - Breakpoints on HTML Elements
tl;dr
In Chrome DevTools in the Elements tab or in Firefox in the Inspector tab you can right click on an element and choose Break on to debug changes related to this element.
Example
DOM Breakpoints can be quite useful to quickly find the JavaScript that is responsible for some (unexpected) behavior. You can use DOM Breakpoints for debugging subtree modifications, attribute modifications or node removal.
Here you can see a very simple example that shows what JavaScript lines are responsible for ...
Debug flaky tests with an Unpoly observeDelay
The problem
Unpoly's [up-observe]
, [up-autosubmit]
and [up-validate]
as well as their programmatic variants up.observe()
and up.autosubmit()
are a nightmare for integration tests.
Tests are usually much faster than the configured up.form.config.observeDelay
. Therefore, it may happen that you already entered something into the next field before unpoly updates that field with a server response, discarding your changes.
The steps I wait for active ajax requests to complete
(if configured) and capybara-lockstep can catch some ...
Git commands to discard local changes
Use case
You have uncommited changes (you can always check by using git status
), which you want to discard.
Context
Now there are several options to discard these depending on your exact situation.
The headlines will differentiate the cases whether the files are staged or unstaged.
- Staged and unstaged changes
- [Staged changes](https://makandracards.com/makandra/516559-git-commands-to-discard-local-changes#s...
SEO: The subtle differences of robots.txt disallow vs meta robots no-index
The robots.txt file and <meta name="robots">
HTML tag can be used to control the behavior of search engine crawlers. Both have different effects.
robots.txt
Marking a URL path as "disallowed" in robots.txt tells crawlers to not access that path.
robots.txt is not a guarantee for exclusion from search engine results.
A "disallowed" URL might be known from an external link, and can still be displayed for a matching search.
Example: even if/admin
is disallowed in robots.txt, `/admin/som...
Rails: Custom validator for "only one of these" (XOR) presence validation
For Rails models where only one of multiple attributes may be filled out at the same time, there is no built-in validation.
I've seen different solutions in the wild, each with different downsides:
- Private method referenced via
validate
: works, but is barely portable and clutters the model. - Multiple presence validations with "if other is blank" each: looks pretty, but is incorrect as it allows both values to be filled in; also the error messages for a blank record are misleading.
Here is a third option: Write a custom validator to ...
Rails: Fixing the memory leak / performance issues in prepend_view_path
Recently we detected a memory leak in one of our applications. Hunting it down, we found that the memory leak was located in Rails' #prepend_view_path
. It occurs when the instance method prepend_view_path
is called in each request, which is a common thing in a multi-tenant application.
On top of leaking memory, it also causes a performance hit, since templates rendered using the prepended view path will not be cached and compiled anew on each request.
This is not a new memory leak. It was [first reported in in 2014](https://github.com/...
A short overview of common design patterns implemented within Rails
The linked content includes a few design patterns implemented with Ruby on Rails.
What is the card indented to achieve?
- You can use the pattern names for code reviews, so all parties know with only a few words which change is requested. Example: "Please use a form object here"
- You can learn about new code patterns
- You should read the sections "Advantages of using design patterns" and "Disadvantages of using design patterns in a wrong way", since design patterns do not replace good code
Included Design Patterns: Service, Value objec...
JavaScript: Testing whether the browser is online or offline
You can use the code below to check whether the browser can make connections to the current site:
await isOnline() // resolves to true or false
Limitations of navigator.onLine
While you can use the built-in function navigator.onLine
(sic), it is only a hint for whether the device can access the Internet.
When navigator.onLine === false
you know for certain that the user device has no connection to the Internet. This mea...
Josh McArthur: Fancy Postgres indexes with ActiveRecord
I recently wanted to add a model for address information but also wanted to add a unique index to those fields that is case-insensitive.
The model looked like this:
create_table :shop_locations do |t|
t.string :street
t.string :house_number
t.string :zip_code
t.string :city
t.belongs_to :shop
end
But how to solve the uniqueness problem?
Another day, another undocumented Rails feature!
This time, it’s that ActiveRecord::Base.connection.add_index supports an undocumented option to pass a string argument as the v...
Debug file system access in a Rails application
It might sometimes be useful to check whether your Rails application accesses the file system unnecessarily, for example if your file system access is slow because it goes over the network.
The culprit might be a library like carrierwave that checks file existence or modification times, whereas your application could determine all this from your database.
Introducing strace
One option it to use strace for this, which logs all system calls performed by a process.
To do this, start your rails server using something like
DISA...
Capybara: Most okayest helper to download and inspect files
Testing file download links in an end-to-end test can be painful, especially with Selenium.
The attached download_helpers.rb
provides a download_link
method for your Capybara tests. It returns a hash describing the download's response:
details = download_link('Download report')
details[:disposition] # => 'attachment' or 'inline'
details[:filename] # => 'report.txt'
details[:text] # => file content as string
details[:content_type] # => 'text/plain'
Features
Compared to [other approaches](...
RSpec: How to turn off partial double verification temporarily
While verifying doubles in RSpec is a good default, it is limited in the amount of methods it actually is able to verify.
The background is that RSpec can't verify dynamically defined methods, which is a known issue for the usage of helper_method and also the reason why [RSpec >= 3.6](http://rspec.info/blog/2017/05/rspec-3-6-has-been-rel...
ActiveRecord: Query Attributes
tl;dr
You can useattribute?
as shorthanded version ofattribute.present?
, except for numeric attributes and associations.
Technical Details
attribute?
is generated for all attributes and not only for boolean attributes.
These methods are using #query_attribute
under the hood. For more details you can see ActiveRecord::AttributeMethods::Query
.
In most circumstances query_attribute
is working like attribute.present?
. If your attribute is responding to :zero?
then you have to be aware that `query_attri...
Version 5 of the Ruby Redis gem removes Redis.current
Redis.current
will be removed without replacement in redis-rb
5.0.
Version 4.6.0 adds deprecation warnings for Redis.current
and Redis.current=
:
`Redis.current=` is deprecated and will be removed in 5.0.
If your application still uses Redis.current
, you can only fix it by no longer using it. Here is how.
Redis.new when you need it
You can easily instantiate a Redis
client when you need it.
There is probably already a constant like REDIS_URL
that you use to configure Sidekiq or similar. So just use that one.
``...
Terminator setup for Procfile-based applications for more comfortable debugging
We use foreman
to start all necessary processes for an application, which are declared in a Procfile
. This is very convenient, but the outputs of all processes get merged together. Especially while debugging you might not want other processes to flood your screen with their log messages.
The following setup allows you to start Terminator in a split view with the Rails server running in the left pane and all remaining processes running via foreman in the right pane. It was heavily inspired by [this card](https://makandracards.com/makandr...
esbuild: Make your Rails application show build errors
Building application assets with esbuild is the new way to do it, and it's great, especially in combination with Sprockets (or Propshaft on Rails 7).
You might be missing some convenience features, though.
Here we cover one specific issue:
Once you have started your development Rails server and esbuild with the --watch
option (if you used jsbundling-rails to set up, you probably use bin/dev
), esbuild will recompile your assets upon change, but build errors will only be printed to the terminal. Your application won't complain about them ...
Carrierwave: How to attach files in tests
Attaching files to a field that is handled by Carrierwave uploaders (or maybe any other attachment solution for Rails) in tests allows different approaches. Here is a short summary of the most common methods.
You might also be interested in this card if you see the following error in your test environment:
CarrierWave::FormNotMultipart:
You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.
If this is a file upload, please check that your upload form is multipart encoded.
Factor...
Capybara: Finding invisible elements and how to test that an element is not visible
When Capybara locates elements in the DOM, by default it allows only accessing visible elements -- when you are using a driver that supports it (e.g. Selenium, not the default Rack::Test
driver).
Consider the following HTML:
<div class="test1">One<div>
<div class="test2">Two</div>
With some CSS:
.test1 { display: block }
.test2 { display: none }
We will be using Capybara's find
below, but this applies to any Capybara finder methods.
Default: visible: :visible
or visible: true
As described above, by defa...
Caching in Rails < 6.1 may down parts of your application when using public cache control
Proxy caching is a good feature to serve your publicly visible application content faster and reduce load on your servers. It is e.g. available in nginx, but also affects proxies delivered by ISPs.
Unfortunately, there is a little problem in Rails < 6.1 when delivering responses for different MIME-types. Say you have an arbitrary route in your Rails application that is able to respond with regular HTML and JSON. By sending the specific MIME type in the Accept
header, you tell the application to either return HTML (text/html
) or JSON (`t...
New gem: Rack::SteadyETag
Rack::SteadyETag
is a Rack middleware that generates the same default ETag
for responses that only differ in CSRF tokens or CSP nonces.
By default Rails uses Rack::ETag
to generate ETag
headers by hashing the response body. In theory this would enable caching for multiple requests to the same resourc...
The TCF 2.0 (Tranparency and Consent Framework) standard, and what you should know about it
The Interactive Advertising Bureau (IAB) is a European marketing association which has introduced a standard how advertising can be served to users in line with the General Data Protection Regulation (GDPR). This standard is called the TCF 2.0 (Transparency and Consent Framework). If you want to integrate any kind of advertising into a website, chances are the advertising network will require your website to implement that standard. This is a very brief overview of what this means:
The basic idea in the TCF 2.0 ...
Finding ancestors with Capybara
Modern versions of Capybara include a finder method #ancestor
which allows you to find a parental element using CSS or XPath.
If you previously did something like this:
field.find(:xpath, './ancestor::div[contains(@class, "form-group")]')
..and prefer CSS, you may rewrite it:
field.ancestor('div.form-group')
Both versions will return the outermost matching element. Use the #order
option find the closest parent:
field.ancestor('div.form-group', order: :reverse)
Using feature flags to stabilize flaky E2E tests
A flaky test is a test that is often green, but sometimes red. It may only fail on some PCs, or only when the entire test suite is run.
There are many causes for flaky tests. This card focuses on a specific class of feature with heavy side effects, mostly on on the UI. Features like the following can amplify your flakiness issues by unexpectedly changing elements, causing excessive requests or other timing issues:
- Lazy loading images
- Autocomplete in search f...
Semantic HTML
Besides their default styling properties, HTML elements have a semantic meaning. For example, an h1
tag is usually styled with a larger font and bold, while it denotes "the single most important headline in its context".
While CSS enables us to style almost any HTML element like anything that is needed, choosing HTML elements corresponding to the meaning of their content has a few advantages:
- HTML becomes a little clearer
- Edge cases have already been considered and implemented:
- Keyboard support (tabbing, arrow keys)
- State...