mattheworiordan/capybara-screenshot
Using this gem, whenever a Capybara test in Cucumber, Rspec or Minitest fails, the HTML for the failed page and a screenshot (when using capybara-webkit, Selenium or poltergeist) is saved into $APPLICATION_ROOT/tmp/capybara.
Link via Binärgewitter Podcast (German).
Atomic Grouping in regular expressions
A little-known feature of modern Regexp engines that help when optimizing a pattern that will be matched against long strings:
An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the group.
A saner alternative to SimpleForm's :grouped_select input type
SimpleForm is a great approach to simplifying your forms, and it comes with lots of well-defined input types. However, the :grouped_select
type seems to be overly complicated for most use cases.
Example
Consider this example, from the documentation:
form.input :country_id, collection: @continents,
as: :grouped_select, group_method: :countries
While that looks easy enough at a first glance, look closer. The example passes @continents
for a country_id
.\
SimpleForm actua...
Lightweight PDF viewer: MuPDF
MuPDF is a PDF reader that renders very quickly, yet still correctly.
It supports PDF 1.7 and all the fancy shenanigans that evince (Ubuntu's default PDF reader) fails to render properly.
On Ubuntu, MuPDF is available in the Universe sources. Simply install via APT:
sudo apt-get install mupdf
Interaction primarily happens via keyboard, but there is basic mouse support.\
See the manpage for more details on navigating.
One downside: There is no printing support, so if...
When using "render :text", set a content type
When your Rails controller action responds with only a simple text, render text: 'Hello'
may not be what you want. You should not even use it on Rails 4.1+ any more.
By default, a "text" response from a Rails controller will still be a sent as text/html
:
render text: 'Hello'
response.body # => "Hello"
response.content_type # => "text/html"
While this may not be too relevant for a Browser client, the response's content type is simply wrong if you want to send a plain-text response, and can cause trouble. \
For example, con...
Chrome 34+, Firefox 38+, IE11+ ignore autocomplete=off
Since version 34, Chromium/Chrome ignores the autocomplete="off"
attribute on forms or input fields. Recent versions of other browser do the same, although implementation details vary.
This is especially problematic for admin areas because Chrome might automatically fill in a password on a "add new user" forms.
Chrome developers say this is by design as they believe it encourages users to store more complex passwords.
Recommended fix for Chrome and F...
About "unexpected '#' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError)"
The error unexpected 'x' after 'DESCENDANT_SELECTOR' (Nokogiri::CSS::SyntaxError)
(where x
may be basically any character) occurs when the Nokogiri parser receives an invalid selector like .field_with_errors #
or td <strong>
.
In Cucumber, the culprit will be an invalid step definition that builds an invalid selector:
# inside some step definition:
field = find_field(label)
page.send(expectation, have_css(".field_with_errors ##{field[:id]}"))
The above raises the mentioned error if field[:id]
is nil, i.e. the foun...
Making media queries work in IE8 and below
When using @media
CSS queries, Internet Explorer 8 and below will fail to respect them.
Though there are several options (like mediatizr
and css3-mediaqueries
), Respond.js was the only one that worked for me.
If you do not want to pollute your application's default JS file with Respond.js, simply:
-
Create an extra JS file (like
media_queries_polyfill.js
) that loads Respond.js://= require respond-1.4.2
-
Make sure it's added to
config.assets.precompile
-
Embed that JS fi...
Retrieving the class an ActiveRecord scope is based on
Edge Rider gives your relations a method #origin_class
that returns the class the relation is based on.
This is useful e.g. to perform unscoped record look-up.
Post.recent.origin_class
# => Post
Note that #origin_class
it roughly equivalent to the blockless form of #unscoped
from Rails 3.2+, but it works consistently across all Rails versions. #unscoped
does not exist for Rails 2 and is broken in Rails 3.0.
Disabling Spring when debugging
Spring is a Rails application preloader. When debugging e.g. the rails
gem, you'll be wondering why your raise
, puts
or debugger
debugging statements have no effect. That's because Spring preloads and caches your application once and all consecutive calls to it will not see any changes in your debugged gem.
Howto
Disable spring with export DISABLE_SPRING=1
in your terminal. That will keep Spring at bay in that terminal session.
In Ruby, [you can only write environment variables that subproc...
Offtopic: Floppy-disc OS
MenuetOS is an Operating System in development for the PC written entirely in 32/64 bit assembly language. Menuet64 is released under License and Menuet32 under GPL. Menuet supports 32/64 bit x86 assembly programming for smaller, faster and less resource hungry applications.
- Fits on a single floppy, boots also from CD and USB drives
- Responsive GUI with resolutions up to 1920x1080, 16 million colours
- Free-form, transparent and skinnable application windows, drag'n drop
- SMP multiprocessor support with currently up to 8 cpus
- IDE: E...
How to create Rails Generators (Rails 3 and above)
General
- Programatically invoke Rails generators
-
Require the generator, instantiate it and invoke it (because generators are
Thor::Group
s, you need to invoke them withinvoke_all
). Example:require 'generators/wheelie/haml/haml_generator' Generators::HamlGenerator.new('argument').invoke_all
Other ways: Rails invokes its generators with
Rails::Generators.invoke ARGV.shift, ARGV
. From inside a Rails generator, you may call the [inherited Thor methodinvoke(args=[], options={}, config={})
](https://github...
docopt: A promising command line parser for (m)any language
docopt helps you define interface for your command-line app, and automatically generate parser for it.
docopt is based on conventions that are used for decades in help messages and man pages for program interface description. Interface description in docopt is such a help message, but formalized. Here is an example:
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h |...
Rails 2: Refuse response formats application-wide
If you regularly get ActionView::MissingTemplate
exceptions, maybe some bot visits your site requesting silly formats like:
http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'
Just restrict accepted format parameters for the whole application like this:
class ApplicationController < ActionController::Base
before_filter :refuse_silly_formats
private
def refuse_silly_formats
acceptable_formats = %w[html xml pdf]
if par...
AngularJS directive to format a text with paragraphs and new lines
If you are using Angular and want something like Rails' simple_format
which HTML-formats a plain-text input into paragraphs and line breaks, this directive is for you.
Any HTML fragments inside that text will still be escaped properly.
Use it like this, where your text
attribute specifies something available in your current scope:
<simple-format text="email.message"></simple-format>
This is the directive, in CoffeeScript syntax:
@app.directive 'simpleFor...
Ruby: How to camelize a string with a lower-case first letter
If you want to do JavaScript-style camelization, ActiveSupport's String#camelize
method can actually help you out. Simply pass a :lower
argument to it.
>> 'foo_bar_baz'.camelize
=> "FooBarBaz"
>> 'foo_bar_baz'.camelize(:lower)
=> "fooBarBaz"
Listening to bubbling events in Prototype is easy
If you come across an (older) application that is using Prototype instead of jQuery, you may often see events bound to single elements only, like this:
$('foo').observe('change', updateThings);
$('bar').observe('change', updateThings);
$('baz').observe('change', updateThings);
If you are calling only one method in each case, this is unnecessarily ugly. Also, when your page contents have been replaced via AJAX (like sections of a form after choosing something), those event hooks will no longer wo...
No more file type confusion in TextMate2
When using TextMate2 with the cucumber bundle, it does not recognize step definitions (e.g. custom_steps.rb
) as such but believes they are plain Ruby files. But there is help!
Solution
Add these lines to the bottom of your .tm_properties
file (in ~/
for global settings, in any directory for per-project settings):
[ "*_steps.rb" ]
fileType = "source.ruby.rspec.cucumber.steps"
Apparently, this works for any files. Define a regex and specify custom settings. The attached article lists all available configuration options (whic...
CSS: Vertically center with margin: auto
Check out the jsFiddle Demo.
CSS
.absoluteCenterWrapper {
position: relative; /* Declare this element as the anchor point for centering */
}
/* Positioning */
.absoluteCenter {
margin: auto; /* Required */
position: absolute; /* Required */
top: 0; bottom: 0; /* Aligns Vertically */
left: 0; right: 0; /* Aligns Horizontally */
}
/* Make sure the centered element fits into its container. If you know that's the case, you can omit this part. */
.absoluteCenter {
max-height: 100%;
max-width: 100%;
}...
How to remove/disable the automatic XSS protection helper html escaping for Rails 3
How to remove/disable the automatic XSS protection helper html escaping for Rails 3.
This is probably a horrible idea.
Alternatives to drop-down menus
Alternatives to drop-down menus to consider in form design.
Some nifty Rails Rake tasks
Did you know?
rake stats # => LOC per controllers, models, helpers; code ratios, and more
rake notes # => collects TODO, FIXME and other Tags from comments and displays them
rake about # (Rails 3+) => Rails, Ruby, Rake, Rack etc. versions, used middlewares, root dir, etc.
faviconit.com: Super-simple favicon generator
Eduardo Russo was tired of complex favicon creation and created his own favicon generator. It's really easy and allows a lot of image editing before rendering the favicons, in all needed sizes, formats and with the HTML needed to include them!
In Rails applications with Haml:
- put all the favicon files into
/public
- store the HTML to
app/views/layouts/_favicon.html
- add
= render 'layouts/favicon'
to<head>
in your application layout(s)
... and you're all...