...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...

...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:

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...

...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...

...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...

makandra dev

...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...

...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!

...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...

makandra dev

...files for images, fonts etc. Most applications will use a single pack (we often call it main), some applications might for example use separate frontend and backend packs.

...yarn upgrade [package] yarn upgrade [package]@[version] yarn remove [package] Under the hood, Yarn calls npm for you. Do not use the npm command yourself. Do not manipulate package.json yourself...

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...

weblog.jamisbuck.org

...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+

docs.ruby-lang.org

...method. return accepts a value that will be the return value of the method call. Use break to quit from a block and from the method that yielded to the...

...jump out of a block and returns nil or the provided argument to the caller. break # => SyntaxError: Can't escape from eval with break example { break 'break' } # => 'break'

...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...

...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...

...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

makandra Curriculum

...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

makandra dev

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

api.rubyonrails.org

...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...

makandra dev

...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:

makandra dev

...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:

...Array: returns a new array where each object is deep_duped any other Object: calls dup, or self when frozen. If your object has instance variables that are hashes or...

...not a silver bullet and needs to be implemented properly by the object you call it on. Further Reading https://en.wikipedia.org/wiki/Object_copy#Shallow_copy https://makandracards.com/makandra/477919-using-deep_dup-for-copying-whole-hashes-and-array

rspec.info

...to add expectations on objects that will only be created when your code is called. If you have older rspec, you could use expect_any_instance_of, but with the...

...here is `and_wrap_original` validator = method.call(*arguments) # <- the original method (`cast`) is explicitly called expect(validator).to receive(:valid?) # <- a expectation on the then newly created object is added...

makandra dev

...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...