JavaScript: Polyfill native Promise API with jQuery Deferreds
You should prefer native promises to jQuery's Deferreds. Native promises are much faster than their jQuery equivalent.
Native promises are supported on all browsers except IE <=11, Android <= 4.4 and iOS <= 7.
If you need Promise
support for these old browsers y...
murdho/rack-cargo: Batch requests for Rack APIs
rack-cargo gives your API a new /batch
route that lets clients perform multiple API calls with a single request.
The batched calls are resolved internally and are then returned as an array of responses:
// This is batch request payload:
{
"requests": [
{
"name": "order",
"path": "/orders",
"method": "POST",
"body": {
"address": "Home, 12345"
}
},
{
"name": "order_item",
...
travisliu/traim: Resource-oriented microframework for RESTful APIs
Use Traim to build a RESTful API for your ActiveRecord models with very little code.
Traim assumes your API resources will map 1:1 to your ActiveRecord models and database tables. This assumption usually falls apart after a few months into a project, so be ready to replace your Traim API with something more expressive afterwards.
Traim outputs a Rack application which you can either serve standalone or mount into your Rails app.
Deleting stale Paperclip attachment styles from the server
Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.
This script has been used in production successfully. Use at your own risk.
# Config #######################################################################
delete_styles = [:gallery, :thumbnail, :whatever]
scope = YourModel # A scope on the class with #has_attached_file
attachment_name = :image # First argument of #has_attached_file
noop ...
ActiveRecord: How to use ActiveRecord standalone within a Ruby script
Re-creating a complex ActiveRecord scenario quickly without setting up a full-blown Rails app can come in handy e.g. when trying to replicate a presumed bug in ActiveRecord with a small script.
# Based on http://www.jonathanleighton.com/articles/2011/awesome-active-record-bug-reports/
# Run this script with `$ ruby my_script.rb`
require 'sqlite3'
require 'active_record'
# Use `binding.pry` anywhere in this script for easy debugging
require 'pry'
# Connect to an in-memory sqlite3 database
ActiveRecord::Base.establish_connection(
ad...
IRB: last return value
In the ruby shell (IRB) and rails console the return value of the previous command is saved in _
(underscore). This might come in handy if you forgot to save the value to a variable and further want to use it.
Example:
irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> _
=> 3
irb(main):003:0> a = _
=> 3
ImageMagick: How to auto-crop and/or resize an image into a box
Auto-cropping
ImageMagick can automatically crop surrounding transparent pixels from an image:
convert input.png -trim +repage output.png
You need to +repage
to update the image's canvas, or applications will be randomly confused.
Trimming specific colors is also possible, see the documentation.
Resizing into a box
Occasionally, you want to resize an image to a maximum width or height, and change the "outer" image dimensions to something that won't match the input image.
To re...
RSpec's hash_including matcher does not support nesting
You can not use the hash_including
argument matcher with a nested hash:
describe 'user' do
let(:user) { {id: 1, name: 'Foo', thread: {id: 1, title: 'Bar'} }
it do
expect(user).to match(
hash_including(
id: 1, thread: {id: 1}
)
)
end
end
The example will fail and returns a not very helpful error message:
expected {:id => 1, :name => "Foo", :thread => {:id => 1, :title => "Bar"}} to inc...
Guide: How to use our (maybe in future) default rubocop config
Follow the instructions here.
PRs at makandra/rubocop-config are welcome. Also check the issue tracker.
RubyMine
Since version 2017-1 RubyMine runs cops in the background, and displays RuboCop offenses the ...
Know what makes your browser pant
I figure we needed a definitive reference for what work is triggered by changing various CSS properties. It's something I get asked about often enough by developers, and while we can do tests with DevTools, I have both the time and inclination to shortcut that for everyone. I'm nice like that. —Paul Lewis
ActiveRecord::RecordNotFound errors allow you to query the :name and :id of the model that could not be found
ActiveRecord::RecordNotFound
errors provide quite meaningful error messages that can provide some insight on application details. Consider the following:
ActiveRecord::RecordNotFound: Couldn't find Organisation::Membership with 'id'=12 [WHERE "organisation_memberships"."user_id" = 1]
You should probably not simply render those error messages to the user directly. Instead you you might want to re-raise your own errors. ActiveRecord::RecordNotFound
provides you with methods :model
and :id
where you can get information about w...
Rails: wrap_parameters for your API
Rails 5 (don't know about the others) comes with an initializer wrap_parameters.rb
. Here you can tell rails to wrap parameters send to your controllers for specific formats into a root node which it guesses from the controller name.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
This would wrap a flat json body, like
{"name": "Konata"}
that gets send to your UsersController
into
{"name" => "Konata", "user" => {"name" => "Konata"}}
Note that the params are now duplicat...
Rails: Configure ActionController to raise when strong params are invalid
Put the line below in the respective env.rb
file to make your action controllers raise an ActionController::UnpermittedParameters
error when strong params are not valid. This might come in handy when you are implementing an API and you want to let the user know that the request structure was invalid. You can then rescue those errors by implementing a rescue_from
to have a generic handling of those cases. Note that you might need to whitelist common params such as :format
to not raise on valid requests.
config.action_controller.a...
Selenium cannot obtain stable Firefox connection
When using geordi for integration tests you might get the following error when trying to run geordi cucumber
:
unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) (Selenium::WebDriver::Error::WebDriverError)
This means, that the vnc window the tests is talking to has no proper firefox version running. To figure out the issue this might help you:
- Check if the
.firefox-version
(e.g.24.0
) is the same as~/bin/firefoxes/24.0/firefox
says in the browser - Maybe [rest...
How to: Snom 300 firmware update
First, go to the webinterface of your phone.
Choose Software Update
in the navigation on the left.
Next, you have to find the current firmware version for your model in the snom wiki. To do this, you have to follow the ?
next to the Firmware
text field to this page and then follow the link of the current firmware below Firmware Versions
in the wiki. Now select your phone model. Next you have to choose between the minor versions. Follow the link of the most recent stable versio...
Snom 300 with headset: Unlink ringtone volume from headset volume
If your Snom 300 always keeps the same volume for headset and ringtone (as soon as you change one you also change the other), here's what to do:
Go to your phone settings web interface, then Preferences
(German Präferenzen
). There is the seemingly harmless setting for Ringer Device from Headset
(German Klingeltonausgabe bei Kopfhörer
). Choose one: "Headset" or "Speaker". Do not select both, otherwise the ringtone volume will always be the same as the headset speaker volume!
Ubuntu: Share internet connections with other computers
You can configure a Ubuntu system as a gateway in order to share it's internet connection (maybe via WLAN or tethering) with other computers on the network.
On the gateway
- Enable ip traffic forwarding:
-
Open
/etc/sysctl.conf
-
Uncomment the line
net.ipv4.ip_forward=1
-
Reload using
sudo sysctl -p /etc/sysctl.conf
-
- Reconfigure ip_tables to allow NAT:
- Download the attached file
- Replace
online_device
with the name of the network device that provides the internet connection
...
How to make select2 use a Bootstrap 4 theme
select2 is a great jQuery library to make (large) <select>
fields more usable.
For Bootstrap 3 there is select2-bootstrap-theme.
It won't work for Bootstrap 4, but rchavik's fork does (at least with Bootstrap 4 Alpha 6, current version at time of writing this).
It is based on a solution by angel-vladov and adds a few fixes.
Use it by addi...
Capistrano: Doing things on rollback
Capistrano has the concept of a "rollback" that comes in really handy in case of errors. When you notice that your recent deploy was faulty, run cap deploy:rollback
and you're back with the previous release. In case of an error during a deployment, Capistrano will rollback itself.
But, you may ask, how can it know how to revert all the custom stuff I'm doing during deployment? It can't. But you can tell it how to.
Capistrano 3
Deploy and rollback are nearly identi...
How to make Webpacker compile once for parallel tests, and only if necessary
Webpack is the future. We're using it in our latest Rails applications.
For tests, we want to compile assets like for production.
For parallel tests, we want to avoid 8 workers compiling the same files at the same time.
When assets did not change, we do not want to spend time compiling them.
Here is our solution for all that.
Its concept should work for all test suites.
Copy the following to config/initializers/webpacker_compile_once.rb
. It will patch Webpacker, but only for the test
environment:
# Avoid hardcoded asset host...
Cucumber: Test that an element is not overshadowed by another element
I needed to make sure that an element is visible and not overshadowed by an element that has a higher z-index
(like a modal overlay).
Here is the step I wanted:
Then the very important notice should not be overshadowed by another element
This is the step definition:
Then(/^(.*?) should not be overshadowed by another element$/) do |locator|
selector = selector_for(locator)
expect(page).to have_css(selector)
js = <<-JS
var selector = #{selector.to_json};
var elementFromSelector = document.querySelector(selector)...
Caution: Carrierwave has your file three times (temporarily)
When storing a file with Carrierwave, it is always cached prior to actually storing it (to support form roundtrips).
Carrierwave by default 1) copies the file to the cache and then 2) copies it again to its final destination (deleting the cached file immediately after storing). This means there are 3 (three) instances of a file on the disk at some point in time, and still 2 instances after Carrierwave is done if you do not remove...
Ruby: define a class with Struct.new
This card will show you a cool way to define a class using Struct.new.
A common usecase for Structs are temporary data structures which just hold state and don't provide behaviour. In many cases you could use a simple hash as a data structure instead. However, a Struct provides you with a nice constructor, attribute accessors and complains if you try to access undefined attributes. Structs are easy to compare (by attributes). A struct gives meaning to the data.
Disclaimer
Structs are great...
How to: Rails cache for individual rspec tests
Rails default config uses the ActiveSupport::Cache::NullStore
and disables controller caching for all environments except production:
config.action_controller.perform_caching = false
config.cache_store = :null_store
If you want to test caching you have at least two possibilities:
- Enable caching for every test (not covered by this card and straightforward)
- Enable caching for individual test
Enable caching for individual test (file cache)
1. Leave the default c...