...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...
...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...
...timer is a timeout that, when triggered, schedules itself again and again. Because $timeout returns a promise for the timer's execution, and because Coffeescript uses the last expression in...
...a block as implicit return value, this pattern is a great way to create an infinitely growing object graph. More details here. This code leaks more and more memory over...
...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...
...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
...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...
...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...
...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...
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...
...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...
const path = require('path') const hq = require('alias-hq') function escapeStringRegexp(string) { return string .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') .replace(/-/g, '\\x2d') } const mapAliasedPath = hq.get(({ rootUrl, baseUrl, paths }) => { return (importPath) => {
...importPath.includes('@')) { return importPath } const basePath = path.join(rootUrl, baseUrl) for (const [aliasedPath, replacements] of Object.entries(paths)) { const regexp = new RegExp('(^|.*/)' + escapeStringRegexp(aliasedPath).replace('\\*', '(.*)')) importPath = importPath.replace(regexp, path.join(basePath, replacements[0]).replace...
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.
...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...
...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...
...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...
...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...
...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...
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...
...frozen, tainted and singleton methods are ignored (like dup) Behavior depends on implementation Hash: returns a deep copy, i.e. referenced objects/values will be deep_duped as well Array: returns a...
...the following three possible values: critical, medium, low. Sorting with Issue.all.order(criticality: :desc) will return the following order: The 'medium' issue The 'low' issue The 'critical' issue This happens because...
...TYPE criticality AS ENUM ('low', 'medium', 'critical'); Sorting with Issue.all.order(criticality: :desc) will now return the following order: The 'critical' issue The 'medium' issue The 'low' isse
...binary cannot run at all, but won't raise an error if the binary returns an exit code > 0. This will instead be reflected in status. stdout_str, error_str...
...str = stderr.read # read stderr to string status = wait_thr.value # will block until the command finishes; returns status that responds to .success? etc end This form is useful for long running commands...
...e.g. Article#name becomes Article#name_de and Article#name_en and Article#name returns the variant in the current locale. You also need a migration strategy to fill those...
...You can set it up to store timestamps as UTC in the database, but return magic, zone-aware values when accessing ActiveRecord time or date attributes. In practice this solution...
}).observe({ type: 'largest-contentful-paint', buffered: true }) // Helpers ///////////////////////////////////////////////////////////////////// function dedupe(arr, key) { return [...new Map(arr.map((item) => [item[key], item])).values()] } function getActivationStart() { const navEntry = getNavigationEntry() return (navEntry...
...getNavigationEntry() { const navigationEntry = self.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0] if ( navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now() ) { return navigationEntry } } When optimizing LCP, these extra steps may be helpful: # media_performance_steps.rb Then(/^the image "(.*)" should...
Let's say we want Peter to respond to a method age that returns his age. On the other hand, Alice should not respond to this method as you...
...is empty, it's just discarded. Careful: In peter's case peter.class does not return his eigenclass now. It still returns User. This means the klass reference in the C...