There are two ways to define a class method from a Modularity trait. Note that the usual caveats regarding class method visibility apply.
The recommended way is to define a method on your module's singleton class:
module SomeTrait
as_trait do
define_singleton_method :foo do
# ...
end
end
end
Using def (has...
When you are calling a method that may raise an exception that you don't care about, you might think of doing something like this:
@user = User.power_find(something) rescue User.new
Do not do that! You will be rescuing away StandardError
and all its subclasses, like NameError
-- meaning that even a typo in your code won't raise an error.
Instead, rescue the exception type that you are expecting:
@user = begin
User.power_find(something)...
Let's assume that we have a model Movie
that registers a callback function when a new instance of Movie
is created (Note: For the purpose of this card it is not important what that callback does or which type of callback it is).
This is how we test whether the callback function (here it is named :my_method
) is called when a new movie is created:
expect_any_instance_of(Movie).to receive(:my_method)
create(:movie) # <-- this is where the method :my_method should be called
You might expect that when calling `create(:mo...
The linked article found a simple way to rewrite legacy git aliases to make them work with differently named default branches
master
. Define it as the global init.defaultBranch
git configuration :git config --global init.defaultBranch master
# cd /path/to/project, then run:
git config ...
I recently enjoyed debugging a Cucumber step that tried to be retryable using a patiently
block:
Then /^"([^"]*)" should( not)? be selected for "([^"]*)"$/ do |value, negate, field|
patiently do
field = find(:label, text: field)['for'].delete_suffix('-ts-control')
...
end
end
Unfortunately this block is not retryable:
field
.field
, instead of the o...Using ActiveRecord's #signed_id
and .find_signed
methods you can create URLs that expire after some time. No conditionals or additional database columns required.
Wondering how a specific method on an object is exactly named? You can use Enumerable#grep
to detect it in the array of methods.
@user.methods.grep /name/ # => [:name, :first_name, :last_name]
You can also call #private_methods
or #public_methods
. To find only relevant methods, it is suggested to subtract generic methods like this:
User.methods - Object.methods
User.methods - ActiveRecord::Base.methods
@user.methods - Object.instance_methods
@user.methods - ActiveRecord::Base.instance_methods
By pressing Ctrl
+ Shift
+ V
you can select a recently copied string for pasting.
Ruby's sort
method doesn't work as expected with special characters (like German umlauts):
["Schwertner", "Schöler"].sort
=> ["Schwertner", "Schöler"] # you probably expected ["Schöler", "Schwertner"]
Also numbers in strings will be sorted character by character which you probably don't want:
["1", "2", "11"].sort
# => ["1", "11", "2"] # you probably expected ["1", "2", "11"]
Also the sorting is case sensitive:
["...
Bundler so far ignored the version specified under BUNDLED_WITH
in the Gemfile.lock
. This had two annoying consequences:
Gemfile.lock
, you got an error message and had to manually install the correct version.Gemfile.lock
, bundler silently updated the version in the Gemfile.lock
to your system's bundler version. To avoid this, you had to always specify, which version you want to use for each bundler c...TLDR
if you define a equality method for a class you must also implement
def hash
.
Ruby has a lot of methods that have to do something with equality, like ==
, ===
, eql?
, equal?
. This card should help you differentiate between those and give you hints on how to implement your own equality methods in a safe manner.
==
When you compare two objects in ruby, you most often see the use of foo == bar
. By default the ==
operator inherits from Object
and is impl...
Our CI setup frequently sees this error while running yarn install
:
yarn install v1.22.19
[1/4] Resolving packages...
[2/4] Fetching packages...
error An unexpected error occurred: "https://registry.yarnpkg.com/typescript/-/typescript-3.9.7.tgz: unexpected end of file".
info If you think this is a bug, please open a bug report with the information provided in "/builds/projects/foo-app/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
This error is caused by [Yarn not retryin...
To read the current breakpoint tier in JavaScript, employ this CSS:
:root {
--current-breakpoint-tier: xs;
@media (min-width: $screen-sm-min) {
--current-breakpoint-tier: sm;
}
@media (min-width: $screen-md-min) {
--current-breakpoint-tier: md;
}
@media (min-width: $screen-lg-min) {
--current-breakpoint-tier: lg;
}
@media (min-width: $screen-xl-min) {
--current-breakpoint-tier: xl;
}
@media (min-width: $screen-xxl-min) {
--current-breakpoint-tier: xxl;
}
}
Then use this JavaScript:
Timecop is a great gem to set the current time in tests. However, it is easy to introduce flakyness to your test suite when you forget to reset the time after the test.
This might be the case if:
Often you only notice these kinds of errors in rare cases when tests are executed in a particular order.
A way to avoid this is by using block notation (`Timecop.travel(...) ...
Usually, design development starts with drafts, sketches and prototypes. These are reviewed, refined and iterated until the final design is ready – shiny, accepted and ready for implementation. I believe this works well when you get to work with the final decider in person.
However, this approach is not successful when the customer has complex internal structures ("Enterprise"). While the drafts and iterations might be all approved by the department you're working directly with ("Fachbereich"), deciders further up the hierarchy (the CEO, po...
From at least Rails 4, the ActionView tag helper turns Array
values of HTML options into a single space-separated string.
This means you can pass an array to :class
options:
extra_classes = %w[one two]
= link_to 'Dashboard', root_path, class: ['btn', 'btn-primary', *extra_classes]
=> <a href="/" class="btn btn-primary one two">Dashboad</a>
= content_tag 'div', 'Hello World', class: %w[alert alert-info]
=> <div class="alert alert-info">Hello World</div>...
When delivering non-public uploaded files (images, documents etc), one has to decide whether and how to do authorization. The usual approaches are:
send_file
with a regular controller. This is secure, but potentially slow, especially for large collections of images.When going with the "unguessable URL" approach, it is possible to somewhat increase security by using expiring URLs. The idea is to encode the expi...
Today's cameras create huge images, some beyond 50MB. Unless you need to offer this large files, you should always shrink uploaded files to a reasonable resolution.
class ImageUploader < CarrierWave::Uploader::Base
process resize_to_limit: [3000, 3000]
# ...
end
In a JavaScript console, type this:
> 9112347935156469760
9112347935156470000
Ooops. And that's not a float!
This occurs because JavaScript uses double precision floats to store numbers.
So according to IEEE floating point definition only numbers between -(2^53 - 1)
(-9007199254740991) and 2^53 - 1
(9007199254740991) can safely be represented in JavaScript.
Note that ECMAScript 6 will probably also offer [Number.MAX_SAFE_INTEGER
](https://developer.mozilla.org/en-US/docs/W...
To make CSS rules dependent on the screen size, we use media queries:
@media (max-width: 500px) {
// rules for screen widths of 500px or smaller
}
Browsers will automatically enable and disable the conditional rules as the screen width changes.
To detect responsive breakpoints from JavaScript, you may use the global matchMedia()
function. It is supported in all brow...
You cannot use Array#join
on an array of strings where some strings are html_safe
and others are not. The result will be an unsafe string and will thus be escaped when rendered in a view:
unsafe_string = '<span>foo</span>'
safe_string = '<span>bar</span>'.html_safe
[unsafe_string, safe_string].join(' ') # will incorrectly render as '<span>foo</span><span&t;bar</span>'
The solution is not to call html_safe
on the joined array and if you thought it would be, you [don't understand how XSS prot...
Expecting a primitive value as an argument to a method invocation is easy:
expect(object).to receive(:foo).with('arg1', 'arg2')
This expectation would be met with this call:
object.foo('arg1', 'arg2')
But what if the argument is expected to be an object with a given set of methods? E.g. this class with #first_name
and #last_name
methods:
class Person
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
attr_reader :first_name, :last_name
end
``...
TL;DR
Append your locale keys with _html to have them marked as
html_safe
.
When you're localizing a Rails application, sometimes there is this urge to include a little HTML. Be it some localized link, or a set of <em>
tags, you'd like to have it included in the locale file. Example:
# Locale file
en:
page:
text: 'Please visit our <a href="https://www.corporate.com/en">corporate website</a> to learn more about <em>the corporation</em>.'
# HAML
= t('.text')
# Desired output
Please visit our <a href="http...
This guide shows how to create an AngularJS application that consumes more and more memory until, eventually, the browser process crashes on your users.
Although this guide has been written for Angular 1 originally, most of the advice is relevant for all client-side JavaScript code.
To inspect the amount of memory consumed by your Javascripts in Chrome:
Shift + ESC
to see a list of Chrome processes...