Enumerators in Ruby
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'].each.with_index.collect { |name, index| name * index }
# -> ["", "bar", "bazbaz"]
If you write your own each
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
How to write a canonical each
method
To write a m...
OR-ing query conditions on Rails 4 and 3.2
Rails 5 will introduce ActiveRecord::Relation#or
. On Rails 4 and 3.2 you can use the activerecord_any_of
gem which seems to be free of ugly hacks and nicely does what you need.
Use it like this:
User.where.any_of(name: 'Alice', gender: 'female')
^
SELECT "users".* FROM "users" WHERE (("users"."name" = 'Alice' OR "users"."gender" = 'female'))
To group conditions, wrap them in hashes:
User.where.any_of({ name: 'Alice', gender: 'female' }, { name: 'Bob' }, { name: 'Charl...
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
Improving browser rendering performance
As the web is being used for more and more tasks, expectations rise. Not only should web pages offer rich interaction, they must be responsive in both size and interaction.
This imposes a paradoxon that needs to be solved by building performing applications. It's not enough any more to have your web site do crazy stuff, it is also required to do it crazy fast. This card is intended to give you an introduction to this emerging aspect of web development.
Read this introductory [performance study on Pinterest](http://www.smashingmagazine.com/...
Regain unused disk space from OpenStack instances
This is how you regain disk space from OpenStack instances if you are using kvm and qcow.
If your instance used up all configured disk space once the disk file remains big. You can end up in a situation where for example the instance use only 20GB disk space but the disk file on the server has 100GB (or even more).
To resize the disk file do the following:
-
Check storage on the instance:
vm $ df -h Filesystem Size Used Avail Use% Mounted on /dev/vda1 99G 19G 75G 21% / udev 2.0G 12K 2.0...
Angular: Quick and easy animation on changed binding value
With ngAnimate, you can easily animate certain events (see directive support). We'll make use of ngClass
animations to style an element on changed binding value.
Say we have a slider and a separate details container. Each time the slider changes, we want to "flash" the details container by hiding it and fading it back in.
HTML
Add a custom class to the element you want to animate, i.e. the details container:
<div class="details slide-index-{{ currentSlideIndex }}">
{{ co...
Error installing gem with native extension (collect2: error: ld returned 1 exit status)
If you have problems installing a gem and get a error collect2: error: ld returned 1 exit status
it's due to missing development headers of a library (ld
is the linker).
For example, with this output:
$ gem install json
Building native extensions. This could take a while...
ERROR: Error installing json:
ERROR: Failed to build gem native extension.
/home/foobar/.rvm/rubies/ruby-2.2.3/bin/ruby -r ./siteconf20150915-3539-1i9layj.rb extconf.rb
creating Makefile
make "DESTDIR=" clean
make "DESTDIR="
compiling generator.c...
natritmeyer/site_prism
SitePrism gives you a simple, clean and semantic DSL for describing your site using the Page Object Model pattern, for use with Capybara in automated acceptance testing.
The Page Object Model is a test automation pattern that aims to create an abstraction of your site's user interface that can be used in tests. The most common way to do this is to model each page as a class, and to then use instances of those classes in your tests.
If a class represents a page then each element of the page is represented by a method that, when cal...
Migrating legacy jQuery code to .on() and .off()
If you need to upgrade code that uses the old jQuery methods bind
, delegate
, live
, unbind
and die
, the attached article has examples how to migrate to the new on
and off
versions.
httpbin: HTTP Client Testing Service
Some dozen generic API endpoints you can use to test how your HTTP client deals with various responses, e.g.
- a slow connection
- many redirects
- compressed data
I found this useful while debugging an issue with timeouts.
Bootstrap 4 is coming
What's new
- Moved from Less to Sass. Bootstrap now compiles faster than ever thanks to Libsass, and we join an increasingly large community of Sass developers.
-
Improved grid system. We’ve added a new grid tier to better target mobile devices and completely overhauled our semantic mixins.
Opt-in flexbox support is here. The future is now—switch a boolean variable and recompile your CSS to take advantage of a flexbox-based grid system and components. - Dropped wells, thumbnails, and panels for cards. Cards are a brand new co...
Pitfall: has_defaults on virtual attributes are nil when loaded from database, of course …
It smells. Rethink your code design.
Code example with makandra/has_defaults:
class Post < ActiveRecord::Base
has_defaults tags: [] # field in db
has_defaults virtual_tags: [] # no db field
def all_tags
virtual_tags + tags
end
end
> Post.new.virtual_tags
=> [] # ✔
> Post.find(1).virtual_tags
=> nil # ☹
> Post.find(1).all_tags
=> Error: undefined method '+' for nil:NilClass
Continuous Security Testing with Devops - OWASP EU 2014
Interesting talk about a team that integrated automated security testing into their BDD workflow.
There is also a video of the talk.
An auto-mapper for ARIA labels and BEM classes in Cucumber selectors
Spreewald comes with a selector_for
helper that matches an English term like the user's profile
into a CSS selector. This is useful for steps that refer to a particular section of the page, like the following:
Then I should see "Bruce" within the user's profile
^^^^^^^^^^^^^^^^^^
If you're too lazy to manually translate English to a CSS selector by adding a line to features/env/selectors.rb
, we already have an [auto-mapper to translate English into ...
passenger problems with upgraded rails-app
You may encounter problems with passenger starting an application with an updated rails.
If you find an error like this in the apache error log:
[ 2015-08-21 10:53:04.1266 17680/7f4909bf7700 Pool2/Implementation.cpp:883 ]: Could not spawn process for group /var/www/example.com/current#default: An error occured while starting up the preloader.
in 'void Passenger::ApplicationPool2::SmartSpawner::handleErrorResponse(Passenger::ApplicationPool2::SmartSpawner::StartupDetails&)' (SmartSpawner.h:455)
in 'std::string Passenger::Appli...
postgresql create extension without giving the application superuser rights
If you need a postgresql extension for your database it isn't a good idea to give your applications database user superuser rights (like many people on stackoverflow think)
Just login to the database with a superuser account (e.g. postgres) and create the extension with it.
Example:
# with the default configuration of postgresql you normally can login as `postgres` user
# without a password if you use the systems `postgres` user
$ sudo su -l postgres
$ pgsql
postgres=# \c your_database;
psql (9.3.9, server 9.3.5)
You are now connected...
How to deal with 'parent id missing' error in nested forms
tl;dr
- Use form models to handle this problem
- Or soften the validation to
validates_presence_of :parent
Usually you would validate presence of parent object id, like in this example:
class Parent < ActiveRecord::Base
has_many :nested, :inverse_of => :parent
accepts_nested_attributes_for :nested
end
class Nested < ActiveRecord::Base
belongs_to :parent
validates_presence_of :parent_id # <-
end
With the parent already persisted creating nesteds still works fine.
But one will encounter a *'parent id missing' er...
How to silence thin boot messages
Each time thin
boots, it prints a boot message :
Thin web server (v1.6.3 codename Protein Powder)
Maximum connections set to 1024
Listening on localhost:36309, CTRL+C to stop
If you are running parallel tests with thin
, this will clutter you output. Disable thin
logging with these lines:
# e.g. in features/support/thin.rb
require 'thin'
Thin::Logging.silent = true
Note that this disables all logging in tests. Instead, you also might set a different logger with `Thin::Loggi...
How to split config/routes.rb in Rails 4
A word of caution
There should rarely be a reason for you to split up config/routes.rb
. If you need to, probably your whole application should be split up.
Split it anyway
Rails::Engine
looks at config.paths['config/routes.rb']
and registers its value with app.routes_reloader
. This means you could put routing files anywhere and then require them. However, I recommend to put any routing files into config/routes/
:
# config/routes/example.rb
Rails.application.routes.draw do
resources :example
end
After creating y...
marco-polo improves your Rails console prompt
MarcoPolo shows your app name and environment in your console prompt so you don't accidentally break production
Officially supporting IRB (standard rails console) and pry (via pry-rails gem).
Example:
$ rails console
Loading development environment (Rails 4.2.1)
agencyapp(dev)>
List of Helpful RubyMine Shortcuts
Navigation
CTRL + SHIFT + ALT + N
-
Search for any symbol in your application, like CSS classes, Ruby classes, methods, helpers etc.
CTRL + SHIFT + N
-
Search for filename in your application (also dependencies)
CTRL + E
-
Open a list of recently opened files
ALT + POS1
-
Open a the navigation bar as a context menu. Allows you to quickly navigate between files.
CTRL + G
-
Go to line
Actions
:...
PostgreSQL: Be careful when creating records with specific ids
In tests, it is sometimes useful to create records with specific ids. On PostgreSQL this can cause problems:
Usually, PostgreSQL uses an "autoincrement" sequences to provide sequential ids for new database rows. However, these sequences will not increment if you insert a record "by hand". This will cause an error:
record = Record.create!
record.id # => 100, next automatic id will be 101
Record.create!(id: record.id + 1) # okay, but next automatic id will still be 101
Record.create! ...
Jasmine: Testing complex types for equality
Jasmine comes with two matchers that test for equality. The first is toBe
:
expect(first).toBe(second)
toBe
passes when first === second
. Unfortunately this is useless for non-primitive values because JavaScript is a horrible language.
However, Jasmine comes with another matcher toEqual
:
expect(first).toEqual(second)
This matcher behaves as a human would expect for types like the following:
- Arrays
- Objects
- Nested array/object constructs
- Regular expressions...
Mocking time in Jasmine specs
The easiest way to freeze or travel through time in a Jasmine spec is to use the built-in jasmine.clock()
.
- After
jasmine.clock().install()
you can use it to controlsetTimeout
andsetInterval
. - Using
jasmine.clock().mockDate()
you can mocknew Date()
(which returns the current time in Javascript)
While you can use SinonJS Fake timers, using the built-in Jasmine clock will save you an extra dependency.