Events triggered by jQuery cannot be observed by native event listeners
jQuery has a function $.fn.trigger()
. You can use it to dispatch an event on a jQuery object:
let $element = $('.foo')
$element.trigger('change')
A caveat is that such an event will be received by jQuery event listeners, but not by native event listeners:
let $element = $('.foo')
$element.on('change', event => console.log('I will be called'))
$element[0].addEventListener('change', event => console.log("I WON'T be called"))
$element.trigger('change')
This is not an issue when your entire app is ...
How to reload a belongs_to association
To reload a single-item association in Rails 5+, call #reload_<association>
:
post.reload_author
In older Railses you can say
post.author(true)
Ruby: How to use prepend for cleaner monkey patches
Let's say you have a gem which has the following module:
module SuperClient
def self.foo
'Foo'
end
def bar
'Bar'
end
end
For reasons you need to override foo
and bar
.
Keep in mind: Your code quality is getting worse with with each prepend
(other developers are not happy to find many library extensions). Try to avoid it if possible.
- Add a
lib/ext/super_client.rb
to your project (see How to organize monkey patches in Ruby on Rails projects) - Add the extension, which ov...
Capybara: Quick checking for element presence (without retries or timeout)
Element finding is a central feature of Capybara. Since #find
is normally used to get elements from the current page and interact with them, it's a good thing that some Capybara drivers (e.g. Selenium) will wait an amount of time until the expected element shows up. But if Capybara cannot #find
it at all, you'll get an error.
if page.find('.that-element')
# Do something
else
# Never happens because #find raises
end
In order to simply check whether an element is present, without errors raised, you can use #has_css?
. It...
ImageMagick: Converting SVG to raster image formats like PNG or JPEG
Conversion
ImageMagick can convert SVGs to raster image formats.
Example for PNG:
convert input.svg output.png
If the SVG has a size of 24x24 (viewBox="0 0 24 24
"), the resulting PNG will also have a size of 24x24.
Resizing
An SVG's viewBox
specifies the intended size, but vector image formats can be scaled freely.
Resize flag (poor results)
If you want your raster image to be larger, the naive approach would be to use the resize
flag.
convert -resize 96x96 input.svg output.png
However, this resu...
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 ...
Ad blockers: How to debug blocked elements
Some users might use Adblock Plus or similar browser plugins to reduce the number of ads displayed. If you run into an issue that your application or part of an application is blocked, this card will give you some guidance on how to debug it.
In general ad blocking is not an issue for most of our web apps. But if your application uses iframes or is embedded in another site it's more prone to it.
Blocked elements most of the time appear to the user as empty frames in the page. The indicator icon of the ad blocker also gives ...
vagrant < 2.2.9: handle conflicting host only adapter
I sometimes had the issue that I received an error when starting an existing vagrant box with vagrant up
:
A host only network interface you're attempting to configure via DHCP
already has a conflicting host only adapter with DHCP enabled. The
DHCP on this adapter is incompatible with the DHCP settings. Two
host only network interfaces are not allowed to overlap, and each
host only network interface can have only one DHCP server. Please
reconfigure your host only network or remove the virtual machine
using the other host only networ...
Why two Ruby Time objects are not equal, although they appear to be
So you are comparing two Time
objects in an RSpec example, and they are not equal, although they look equal:
expected: Tue May 01 21:59:59 UTC 2007,
got: Tue May 01 21:59:59 UTC 2007 (using ==)
The reason for this is that Time
actually tracks fractions of a second, although #to_s
doesn't say so and even though you probably only care about seconds. This means that two consecutive calls of Time.now
probably return two inequal values.
Consider freezing time in your tests so it is not dependent on the speed of the executi...
Rspec: Scope your custom matchers to example groups
When you find yourself in the situation that you would like to define a custom matcher in your specs, but you do not want to define a global matcher since you need it only for your specific test, there are two ways to do it:
Custom matcher for a single group
If you're only going to include
a matcher once, you can also use the matcher
macro within an example group:
describe "group" do
matcher :...
Google Chrome now has a JavaScript bundle visualizer
Similar to the Webpack Bundle Analyzer, Chrome's new Lighthouse feature …
… shows a visualisation of your JavaScript bundles. It's compatible with sourcemaps and is great for understanding large JavaScript modules used by your page. It can also visualise unused bytes.
This is very helpful to visualize Javascript files in development. It also works on production code, where its usefulness depends on the structure of the productive Javascr...
no passenger served applications running error when deploying via capistrano
When deploying with capistrano it's possible you get this "error" message:
*** [err :: example.com] There are no Phusion Passenger-served applications running whose paths begin with '/var/www/example.com'.
*** [err :: example.com]
This is just because there were no running passenger process for this application on the server which could be restarted. It's not a real error. The application process will start if the first request for this app hits the appserver.
The output appears as err
because it's printed to stderr
.
Dep...
Load order of the environment
Rails 3, 4, 5, 6
config/application.rb
-
config/environment.rb
before theinitialize!
call (we don't usually edit this file) - The current environment, e.g.
environments/production.rb
- Gems
- Vendored plugins
- All initializers in
config/initializers/*.rb
-
config/environment.rb
after theinitialize!
call (we don't usually edit this file) - Your own code from
app
Rails 2
- Code in
config/preinitializer.rb
(if it exists) -
environment.rb
, code above theRails::Initializer.run
blo...
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)
Hints for debugging MySQL InnoDB deadlocks
Deadlocks only occur if two transactions in separate threads compete for the same rows in the database. They usually (but not necessarily) only happen when trying to update or otherwise lock several rows in different order.
Solving deadlocks is potentially complicated, so here are a few pointers:
- MySQL should always detect the deadlock right when it happens, and will throw an error to one of the offending threads. This error states the SQL statement that this thread was currently waiting for, and that tried to acquire one of the competin...
Advisory: Excel converts CSV entries to formulas
If your application exports CSV, be advised that Excel and other spreadsheet applications treat certain cells (those starting with =
, +
, -
or @
) as formulas.
This is an issue if you output user input. Not only is it probably not what you want, it also poses a security risk. See the link for attack vectors.
Note that current Excel versions will warn the user when opening the file. At least for the code execution vulnerability, these three warnings seems adequate to me.
Code execution warnings:
![Image](/makandra/47624/attach...
You can use graphs in gitlab comments!
Since GitLab 10.3. you can use Mermaid in GitLab comments: Gitlab Doc.
With Mermaid you can create diagrams based on text / code.
Sometimes a picture says more than thousand words and can help you express your thoughts more clearly.
Some Examples from the Mermaid documentation:
Flowcharts
graph TD;
A-->B;
A-->C...
Strict Loading Associations can prevent n+1 queries
Rails 6.1 has a "strict loading" mode that forces the developer to preload any association they plan to use. Associations no longer load lazily. An error is raised when reading an association that was not preloaded.
Enabling strict loading is a tool to prevent n+1 queries.
Strict loading can be enabled for individual records, for a single association, for an entire model, or globally for *all...
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...
Setup Sidekiq and Redis
If you want Sidekiq to be able to talk to Redis on staging and production servers, you need to add the following to your configuration:
# config/initializers/sidekiq.rb
require 'sidekiq'
Sidekiq.configure_client do |config|
config.redis = { url: REDIS_URL }
end
Sidekiq.configure_server do |config|
config.redis = { url: REDIS_URL }
end
The following step may be skipped for new Sidekiq 6+, since it isn't recommended anymore to use a global redis client.
# config/initializers/redis.rb
require 'redis'
require_relativ...
RSpec: how to prevent the Rails debug page if you want to actually test for 404s
Within development and test environments, Rails is usually configured to show a detailed debug page instead of 404s. However, there might be some cases where you expect a 404 and want to test for it.
An example would be request-specs that check authorization rules. (If you use a gem like consul for managing authorization rules, you should always check these rules via power-specs. However, request-specs can be used as a light-weight version of integration tests here.)
In this case, Rails will replace the 404 page that you want to test ...
RSpec: automatic creation of VCR cassettes
This RailsCast demonstrated a very convenient method to activate VCR for a spec by simply tagging it with :vcr
.
For RSpec3 the code looks almost the same with a few minor changes. If you have the vcr
and webmock
gems installed, simply include:
# spec/support/vcr.rb
VCR.configure do |c|
c.cassette_library_dir = Rails.root.join("spec", "vcr")
c.hook_into :webmock
end
RSpec.configure do |c|
c.around(:each, :vcr) do |example|
name = example.metadata[:full_descripti...
RSpec: ". not_to include" behaves like ".to exclude"
RSpec is smart when using the include
-matcher in combination with .not_to
. One could assume that
.not_to include(3, 4, 5)
evaluates to:
NOT( .to include(3, 4, 5) )
However, it behaves like:
.to (NOT include(3) && NOT include(4) && NOT include(5) )
Warning
Using
.not_to
in combination with theinclude
-matcher doesn't logically negate the final truth value. It instead negates the individual include-expectations for each argument.
Proof
describe 'RSpec' do
it "doesn't use logical nega...
A Guide To CSS Debugging
Debugging in CSS means figuring out what might be the problem when you have unexpected layout results. We’ll look at a few categories bugs often fit into, see how we can evaluate the situation, and explore techniques that help prevent these bugs.