Script outputs 'script 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...
...is the model of Ruby, 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...
...like record.errors.full_messages. With simple ActiveRecord models If you have class Cat < ApplicationRecord, the call to Cat.human_attribute_name(:name) will look for translations in the following places: activerecord.attributes.cat.name activerecord.attributes.name...
With subclasses If you have class Cat < Animal, the call to Cat.human_attribute_name(:name) will look for translations in the following places: activerecord.attributes.cat.name activerecord.attributes.animal.name activerecord.attributes.name (avoid) With namespaced...
...use ActionDispatch::ShowExceptions use ActionDispatch::DebugExceptions use BetterErrors::Middleware use ActionDispatch::Reloader use ActionDispatch::Callbacks use ActiveRecord::Migration::CheckPending use ActionDispatch::Cookies use ActionDispatch::Session::CookieStore use ActionDispatch::Flash
...Head in this example def initialize(app) @app = app end # This middleware will be called by ActionDispatch::ContentSecurityPolicy::Middleware def call(env) # env may be modified here (request pre-processing...
...attribute of the model. Though 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...
...field gets cleared and the transaction commits, then the file gets deleted in a callback. Using the dynamic #remove_avatar! method Carrierwave patches onto the model user.remove_avatar! user.save!
...Use it like this: page.evaluate_async_script(<<~JS) let [done] = arguments 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) let [done] = arguments doSomethingAsynchronous().then(() => { done("some result") }) JS Finally, you can pass additional object from Ruby to Javascript:
...a "block of code". There are 2 "flavors" of Procs: Those with "block semantics", called blocks or confusingly sometimes also procs Those with "method semantics", called lambdas lambdas
block end test = capture_block do |arg| puts arg end How to call a block Calling a block or a lambda works the same way. There are multiple...
...Introducing strace One option it to use strace for this, which logs all system calls performed by a process. To do this, start your rails server using something like
...file -f bin/rails s The -e trace=file hides all non-file-system related calls. The -f instructs strace to also monitor forks. You will now see your Rails log...
...X = Class.new do #... end which means X is an instance of Class. When you call X.class you will get Class. With an instance of X, however, you will get the...
...instance does and can respond with 42. This is why a such method is called a singleton method. Only one specific instance is allowed to access it, but not all...
...the PID of your Ruby process (e.g. passenger-status) $ sudo gdb -p PID (gdb) call rb_eval_string("$stderr.reopen('/tmp/ruby-debug.' + Process.pid.to_s); $stderr.sync = true") # redirects stderr (gdb) call rb_backtrace...
...the process afterwards, since stderr is now borked. It is possible you have to call rb_backtrace() multiple times to get the full stacktrace. Previous method on Ruby 2.4+
class CacheControl::Middleware MAX_AGE = 60 def initialize(app) @app = app end def call(env) request = ::Rack::Request.new(env) status, headers, body = @app.call(env) # Add surrounding caching logic as...
...you to keep your integration tests as DRY as your application code. Option 1: Call other step definitions This is Cucumbers default way of sharing short setup steps or assertions...
...You can even call step definitions from other step definitions by calling steps: When /^I search for "(.+?)"$/ do |query| steps %{ When I go to the search form And I fill...
...using rails_xss, you need to upgrade by deleting the existing plugin directory and calling script/plugin install https://github.com/rails/rails_xss.git If you are using the native Rails I18n API, open...
...users are signed out when Rails does not receive a valid token. Rails 2.3.11 calls handle_unverified_request for this which you need to overwrite with your logic, like this...
...in the debugging console: Understand your current position in the program Read local variables Call methods that are reachable from the current scope Switch into a full irb console and...
Move the program position one statement ahead Jump into the next method call Jump out of the current method call Exit debugging console and resume program
...proper sub-transactions can lead to unwanted or too early triggering of after_commit callbacks: Unwanted because the inner after_commit callback is still executed if the outer transaction is...
Too early because the inner after_commit callback is executed before the overall commit is persisted to the database. In detail Take for example the following (simplified) model...
...flamegraph" link at the bottom of the request's page. Search for long method calls in the graph and consider fixing those. Caution The gem also allows displaying the flamegraph...
...appending ?pp=flamegraph&flamegraph_ignore_gc=true. But if the controller doesn't explicitly call the render method, the view rendering won't be part of the flamegraph and you...
...to enforce a Date header: class AddDateHeaderMiddleware def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) if headers['Date'].blank? headers['Date'] = Time.now.httpdate end
...expectation failure. The catch-and-retry logic should be built into the functions you call when interacting with the browser: If you're using Capybara, functions like click_link or...
...prove that it both fails and succeeds for a same order. This order is called seed in term of tests. With Cucumber you can run tests like this:
Starting 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...
...method, it is useful to follow the same practice, i.e. write a method that calls a given block for all entries returns an enumerator, if no block is given
...this example weather. Using yield within a partial It's possible for partials to call yield and act like a layout. You can use this to extract common containers in...
...something more sensible if a collection is empty. One can avoid ifs and any? calls in templates and make use of the return value of render. <%= render(@collection) || render('empty...
cache_id && @revalidated_cache_id != cache_id end end end end If you called check_blacklist!(file) and check_content_type_blacklist!(file) in this trait, these lines should...
...active or not. This is done by settings the if:...
...kwarg within the version call. For example, if you migrated legacy videos from the old server, you still want to...
...When a domain name is given, the non-interactive mode is used. Call nslookup without a url to start interactive mode. With interactive mode you just have to type in...
...the first line is your DNS resolver. To use a specific one, you can call nslookup like this: >nslookup heise.de 8.8.8.8 Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer:
...expect { rand(100) }.to produce_different_results, you have to use this syntax and call supports_block_expectations: RSpec::Matchers.define :produce_different_results do |sample_size: 10| supports_block_expectations...
...native element wrapped as a jQuery collection: let $element = $(element) An API object to call additional JavaScript behavior added by a library: var player = flowplayer($element) player.play() Framework activation layers...
Run code on page load Instead use up.compiler() or if (document.readyState != 'loading') callback() else document.addEventListener('DOMContentLoaded', callback) Fast element construction This is something where jQuery really shines:
...in JavaScript (as opposed to the code we usually write in Ruby)? What are "callbacks" in JavaScript? Can you find examples for libraries that use callbacks to deal with asynchronicity...
...for libraries that use promises to deal with asynchronicity? How can you parallelize multiple calls of an async function? Exercises Judging asynchronous code Look at the following code: async function...