...has finished, the animation keyframes will be cleared from the element and it will return to its previous state. You can specify the iterations: Infinity option to loop animations (like...
...with CSS animations). An Animation object is returned that you can use to further control the animation. Waiting for animations to finish Animation#finished returns a promise that allows you...
...this.years = this.days / 365 } humanized(locale = 'de') { const humanizer = new Duration.Humanizer(locale) if (this.minutes < 1) { return humanizer.humanize(this.seconds, 'second') } else if (this.hours < 1) { return humanizer.humanize(this.minutes, 'minute') } else if (this.days...
...return humanizer.humanize(this.hours, 'hour') } else if (this.years < 1) { return humanizer.humanize(this.days, 'day') } else { return humanizer.humanize(this.years, 'year') } } static Humanizer = class { constructor(locale) { this.locale = locale } humanize(number, unit) { const formatOptions = {
...url which you will need. Another solution would be to call a power that returns false for this default route. Rate limiting Now that the public access is denied, a...
if exceeds_storage_limit? render json: { error: "Storage limit exceeded" }, status: :forbidden return end blob = create_blob_and_deduct_storage! render json: direct_upload_json(blob) end
...In the example above, there will be the local variable weather_counter defined, which returns a counter of the currently rendered item in the collection. Furthermore it will add a...
...One can avoid ifs and any? calls in templates and make use of the return value of render. <%= render(@collection) || render('empty_state') %> Caching collections Fragment caching a rendered collection...
...the specific MIME type in the Accept header, you tell the application to either return HTML (text/html) or JSON (text/json). The problem is that Rails caches the response independently from...
...the homepage route of your server that may only respond with HTML. It will return a JSON string {"error":404,"message":"Not found"}. When the cache is controlled publicly, this...
...parameter was blank? and aborted the method execution in this case. def foo(scope) return if scope.blank? # Use scope, e.g. scope.find(...) end We then called this method with an all...
...scope: foo(Media::Document::Base.all). Be careful with this. all returns a scope (ActiveRecord::Relation) which looks and is harmless at first because nothing is loaded into memory at that...
...const felix = { name: "Felix", age: 30, role: "admin" }; greet(felix); // [LOG]: "Hello Felix" // object returned from another function function getUser() { return { name: "Felix", age: 30, role: "admin" }; } greet(getUser()); // [LOG...
function getPoint(): Point2D | null { // We'll just stub this using randomness return Math.random() > 0.5 ? { x: 1, y: 2 } : null; } Union Types Point2D | null is called a union...
...Message.search method that looks for a given query in the body column. It should return a scope (relation) with all matches: Message.search('quarterly results') # => #<ActiveRecord::Relation [...]> This is all we...
...to_tsquery('simple', :query) SQL after_save :index_for_search def index_for_search return unless saved_change_to_subject? || saved_change_to_body? Message.where(id: id).update_all(<<~SQL...
Rails' signed_id works well for this: class FrontendUser < ApplicationRecord # ... def unsubscription_token return unless persisted? signed_id(purpose: :unsubscription) end # ... end Processing the unsubscribe request The unsubscribe endpoint...
...endpoint should accept the POST request triggered by the List-Unsubscribe-Post header and return 200 OK if the unsubscribe succeeds...
...typecast ids with #to_i before comparing them to usual integer ids. select_all Returns an ActiveRecord::Result. This object holds lots of meta info, but can be used as...
...You may call #to_hash or #to_a on the result, which both will return a real Array containing real Hashes. Keys and values are always strings! select_all('SELECT...
...builds a response and passes it back to the last middleware. Each middleware now returns the response until the request is answered. Think of it like Russian Dolls, where each...
...Here, the next middleware in the stack is invoked, passing in `env`. # `@app.call` will return what it receives from Rack::Head. status, headers, body = @app.call(env) # status, headers and body...
...can be polyfilled on older browsers. Example Here is an async function countDown(). It returns a promise that will be fulfilled after the given number of seconds: function countDown(seconds...
...return new Promise((resolve, reject) => { setTimeout(resolve, seconds * 1000) }) } Here is how you would use it: countDown(10).then(() => console.log("10 seconds have passed")) // prints "10 seconds have passed" after...
...to spec/requests/default_etag_spec.rb. You may need to adjust the let :route_with_tokens so it returns a good route within your app. describe 'Default ETag' do let :route_with_tokens do...
allow_any_instance_of(ActionView::Base).to receive(:javascript_include_tag).and_return('script') allow_any_instance_of(ActionView::Base).to receive(:stylesheet_link_tag).and_return('style...
...implemented both a version for loaded Ruby objects (Interval#overlaps?) and a scope that returns all overlapping intervals (Interval.overlapping). Depending on your problem you might need one or both or...
...this interval def overlaps?(other) start_date <= other.end_date && other.start_date <= end_date end # Return a scope for all interval overlapping the given interval, excluding the given interval itself
...helps you to avoid collisions with config options related to Rails itself. The config.x returns an OrderedOptions object for the first two levels, but not deeper. This approach might be...
...Configuration itself and all initializers. It allows to write environment dependent settings. Undefined keys return nil if not present e.g. Rails.application.config.foobar => nil. If you need to ensure the value of...
...options hash, you probably want to use fetch: x = options.fetch(:x, 'default-value') fetch returns the default value only if the key :x is missing from the Hash entirely.
...In the last case, the hash still has a key :x, and fetch will return its value nil. Setting defaults correctly: JavaScript Plain ES5 (no libraries) Prefer to check if...
...Rails load its data from the database again. user.posts.reload # discards cache and reloads and returns user.posts right away # => [...] If you want to discard the cache but not query the database...
...load anything yet user.posts # SQL query happens to load new state # => [...] Note that reset returns the association/scope. Hence, the above will not seem to work on the Rails console, just...
...in time with_advisory_lock! will raise an error whereas with_advisory_lock would return false. # returns false if the lock was not able to be acquired within 10 seconds...
...the database field holds the file name as string, calling the attribute will always return the uploader, no matter if a file is attached or not. (Side note: use #present...
...will delete the file AND empty the database field. Subsequent calls to avatar.present? will return false. Note that Carrierwave itself will NOT touch the database, so you need to save...
lambdas They behave like Ruby method definitions: They are strict about their arguments. return means "exit the lambda" How to define a lambda With the lambda keyword
When the block receives too many arguments, it will discard some return means "exit the surrounding method" for only "exiting the block" use break (takes an argument...
A matcher is a function that returns an object with a compare key. Usually it is registered with beforeEach: beforeEach(() => { jasmine.addMatchers({ // Example matcher toBeAnything() { return { compare(actualValue, ...matcherArguments) { // Do...
...some computations here ... // Return whether the actualValue matches the expectation return {pass: true} } } } }) }) Usage expect(actualValue).toBeAnything(...matcherArguments) When a matcher is invoked, Jasmine will call its compare() function with...
...taskName = options.taskName || `observed changes in ${formOrField}` const delay = options.delay || formOrField.getAttribute('up-watch-delay') || up.form.config.watchInputDelay return up.on(formOrField, 'input change', () => { window.CapybaraLockstep.startWork(taskName) setTimeout(() => window.CapybaraLockstep.stopWork(taskName), delay) }) } } if (window.CapybaraLockstep) { // lock capybara for...
...all changes to fields with callbacks up.compiler('[up-observe]', (formOrField) => { return lockCapybaraForObservedChanges(formOrField, { taskName: `[up-observe]: ${formOrField}` }) }); up.compiler('[up-autosubmit]', (formOrField) => { return lockCapybaraForObservedChanges(formOrField, { taskName: `[up-autosubmit]: ${formOrField}` }) }); up.compiler('[up...
...thoughtfulness of its compressed output. Let's take this function: function fn() { if (a) { return 'foo' } else if (b) { return 'foo' } else { return c() } } console.log(fn()) Terser will reduce this...
...Let's use a similiar input, but call fn() twice: function fn() { if (a) { return 'foo' } else if (b) { return 'foo' } else { return c() } } console.log(fn()) console.log(fn()) This compresses...
ActiveModel classes have a class method .human_attribute_name. This returns a human-readable form of the attribute: Person.human_attribute_name(:first_name) # => "First name" By default Rails will use...
...way you will not duplicate custom names throughout your code base. Also Rails will return the locale values in all methods that mention attribute names, like record.errors.full_messages.