...this.submitButton.disabled).toBe(false) let submitPromise = this.form.onSubmit() // assuming we exposed .onSubmit in our code and return a promise expect(this.submitButton.disabled).toBe(true) submitPromise.then(() => { // form is done expect(this.submitButton.disabled).toBe(false)
...notify Jasmine we're finished }) }) Newer versions of Jasmine allow our specs to simply return a Promise, so we could rewrite this as // slightly better it('disables the submit button...
...safe for unescaped insertion. How html_safe works Calling html_safe on a String returns a new object that looks and acts like a String, but actually is a ActiveSupport...
...String itself. It doesn't change the string at all. All it does is return a SafeBuffer which will handle future concatenations differently than a String. How Rails auto-escapes...
...strip_icc_fields private def strip_icc_fields fields = vips_image.get_fields.select { |field| field.start_with?('icc-') } return if fields.blank? stripped_image = vips_image.mutate do |mutable| fields.each do |field| mutable.remove!(field) end end stripped_image.write...
...CarrierWave::Vips process :strip_all_metadata private def strip_all_metadata fields = vips_image.get_fields return if fields.blank? stripped_image = vips_image.mutate do |mutable| fields.each do |field| mutable.remove!(field) end end stripped_image.write...
Be careful when memoizing a method that returns a scope, e.g.: def variants scoped(:conditions => { :name => name }) end memoize :variants Because of the way memoize is implemented, that method now...
...no longer returns a scope but its loaded target array. The best solution is to use the Memoizer gem instead. A workaround is to roll your own memoization:
...with Ruby 1.9, most #each methods can be called without a block, and will return an enumerator. This is what allows you to do things like ['foo', 'bar', 'baz'].each.with_index.collect...
...same practice, i.e. write a method that calls a given block for all entries returns an enumerator, if no block is given How to write a canonical each method
...twice', function() { // Replace the internal implementation with a Jasmine spy // Note that hello() will return `undefined` unless you call mock().and.callThrough() or callFake()! const spy = hello.mock() helloTwice() expect(spy.calls.count()).toBe...
...mockable(originalFn) { if (window.jasmine) { let name = originalFn.name let obj = { [name]: originalFn } let mockableFn = function() { return obj[name].apply(this, arguments) } mockableFn.mock = () => spyOn(obj, name) // eslint-disable-line no-undef
...one for the validation and one for the submission. Sometimes the validation request would return after the submit request. 💥 Unpoly tried to show the validation error, but the form was...
...ware polling implementation could look like this: up.compiler('[poll]', function(element) { if (isFeatureDisabled('polling')) return // Reload element every 5 seconds. const timer = setInterval(function() { up.reload(element) }, 5_000) // Stop reloading...
...waits until all in-flight requests have finished: module ConcludeBrowserRequests def conclude_browser_requests return unless page.driver.is_a?(Capybara::Selenium::Driver) page.execute_script(<<-JS) window.XMLHttpRequest.prototype.send = function() { // Don't send a...
...request. The readyState will remain at XMLHttpRequest.UNSENT. } window.fetch = function() { // To prevent callbacks, return a promise that never settles. return new Promise(function() {}) } JS Capybara::Lockstep.synchronize end end Note that this...
...how to abort it. Rails 5 does not halt callback chain if false is returned Legacy Rails versions (1-4) Goal Rails version Within before_* Within after_* Cancel later callbacks...
return false return false Rollback the transaction Rails 1-4 return false raise ActiveRecord::Rollback Take care that your callbacks don't accidentally return false, since that...
...is going to be rounded (e. g. an item total), your model should always return or store this amount as a rounded value. No other model should ever see the...
...quantity).round(2) end end Note how when asked for its total, the item returns the total with rounding already performed. It never returns an unrounded total. Assuming that prices...
...start', 'script end', (long delay), '...
Properties of sync APIs function calls are blocking and return a value when they're done easy control flow computer idles while waiting for IO...
...Java, Elixir, PHP, Python, ... Properties of async APIs function calls are non-blocking and return immediately. return values are passed to callback functions. convoluted control flow inherently concurrent computer spends...
let editor = undefined tinymce.init({ target: element, plugins: ['autoresize'], }).then((editors) => { editor = editors[0] }) return () => { if (editor) { editor.destroy() } } }) Note that import is used as a keyword. This causes webpack to...
...put into the main bundle up.compiler('[tinymce]', (element) => { let editor = undefined loadTinyMce() .then(tinyMce => { return tinymce.init({ target: element, plugins: ['autoresize'], }) }) .then((editors) => { editor = editors[0] }) function loadTinyMce() { return Promise.all([
...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...
...the compressed source verbatim: class Klass { constructor(arg) { this.property = arg } publicMethod() { if (this.privateMethod()) { // ... } } privateMethod() { return this.property > 10 } } Mangling private properties While you can tell your minifier to mangle all object...
...with an underscore character: class Klass { constructor(arg) { this._property = arg } publicMethod() { if (this._privateMethod()) { // ... } } _privateMethod() { return this._property > 10 } } You may also use private class fields and prefix internal properties with an...
...create an object without a class: let shape = { width: 30, height: 20, computeArea: function() { return this.width * this.height } } shape.width // => 30 shape.height // => 20 shape.height = 100 Note how "methods" are just properties with...
...a function value: shape.computeArea // => function() { return this.width * this.height } shape.computeArea() // => 3000 Objects are like hashes In many ways a JavaScript object is more like a Ruby Hash or a Java Map...
...discussed equality methods, but by comparing the values of the hash method. hash must return an integer that is equal for objects that are equal according to the eql? method...
end end bob = Person.new('bob') phone_list = { bob => '0821 123', } phone_list[bob] # returns '0821 123' phone_list[Person.new('bob')] # returns nil [bob, Person.new('bob')].uniq [ [0] #<Person:0x0000559054263420...
...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 = {
...foo).with(duck_type(:first_name, :last_name)) To also test that the methods return a particular value, use have_attributes: expect(object).to receive(:foo).with(have_attributes(first...
...Hans', last_name: 'Dampf')) Test that the argument is a certain class and also returns certain values Use the attached object_having matcher to test both class and method return...
...method to show development errors you need to update the isDevelopmentError() function so it returns true when your particular development server shows an error. Warning Unpoly cannot repeat form submissions...
...data-environment="development"]` attribute on your ` ` element. // See https://makandracards.com/makandra/1433-detect-the-current-rails-environment-from-javascript-or-css if (document.body.dataset.environment === 'development') { // Returns true when your development server shows an error page. function isDevelopmentError(response) { return !response.ok && /Full...
doSomethingAsynchronous().then(() => { done() // call this to indicate we're done }) JS You can return results to Ruby by passing them to the done callback: result = page.evaluate_async_script(<<~JS...
...method with some information about the Error. The inclusion of error: true in the return value tells Selenium that an error happened: result = page.evaluate_async_script(<<~JS, arg1, arg2)
}, plugins: [ // ... { name: 'svgo', setup(build) { build.onLoad({ filter: /\.svg$/ }, async ({ path }) => { if (path.includes('/fonts/')) return if (path.includes('/node_modules/')) return const svg = await fs.promises.readFile(path, 'utf8') const { data } = svgo.optimize(svg) return...
...homegrown polyfill e.g. for Element#closest(): if (!Element.prototype.closest) { Element.prototype.closest = function(selector) { if (this.matches(selector)) { return this; } else if (this.parentElement) { this.parentElement.closest(selector) } } } ... or, if you have Unpoly 0.60+: if (!Element.prototype.closest) { Element.prototype.closest...
...function(selector) { return up.element.closest(this, ...args); } } DOM helper libs compared Libary jQuery 86.9 kB minified 30,4 kB gzipped dom4 10.0 kB minfied 4.3 kB gzipped up.element + up.event
Ruby has Enumerable.find(&block), which returns the first item in the collection for which the block evaluates to true. first_post_with_image = posts.find do |post| post.image end However, sometimes...
...with each item. Calling break with an argument will exit the whole block evaluation, returning whatever argument was given to break: first_image_url = posts.find do |post| break post.image.url if...
...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...