Mouse wheel + Shift key = horizontal scrolling
On Ubuntu, you can scroll horizontally with your mouse wheel when holding the Shift key while scrolling.
It does not work in all applications, but many support it.
Alternatives to drop-down menus
Alternatives to drop-down menus to consider in form design.
Count number of weekdays between two dates
If you need to quickly find out the number of weekdays (Monday to Friday) between to given dates, try this:
require 'date'
a = Date.parse "11.04.2014"
b = Date.parse "31.12.2014"
(a..b).count {|date| (1..5).include?(date.wday) }
Ruby on Rails 4 and Batman.js
Batman is an alternative Javascript MVC with a similar flavor as AngularJS, but a lot less features and geared towards Ruby on Rails.
The attached link leads to a tutorial for a small blog written with Rails / Batman.js.
I'm collecting other Batman.js resources in my bookmarks.
JavaScript: How to log execution times to your browser console
If you are trying to inspect timings in JavaScript, you can use console.time
and console.timeEnd
which will write to your browser console.
Example:
console.time('lengthy calculation');
lengthyCalculation();
console.timeEnd('lengthy calculation');
lengthy calculation: 1.337ms
Note that this allows using console.timeEnd
in another context which is helpful when you are doing things asynchronously, or just in different places.
Works in all browsers, including recent Internet Explorers. For older IEs, you may activate...
Techniques for authentication in AngularJS applications
Article about implementing authentication (current_user
) and authorization (access rights) in AngularJS.
Has an surprising amount of practical and understandable code.
Why belongs_to/has_many cannot overwrite methods with the same name
When you use a belongs_to
or has_many
macro you might be surprised that the methods that it generates does not override a method with the same name. Take this example:
class Project < ActiveRecord::Base
def user
"foo"
end
belongs_to :user
end
Project.new.user
still returns "foo"
.
The reason for this is that what belongs_to
does is actually this:
class Project < ActiveRecord::Base
include FeatureMethods
def user
"foo"
end
end
module Project::FeatureMethods
def user
# ass...
ActiveRecord 2.3: Nested attribute changes disappear
There is a bug in ActiveRecord 2.3.x that leads to changes in nested forms getting lost.
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks
end
If you access project.tasks
after setting tasks through the nested attribute logic, all tasks will be reloaded and all changes will be lost. This usually happens
- in validations
- in callbacks
- after validation errors, when rendering the view again
The attached initializer fixes those issues.
Firefox: Remove dotted border from focused buttons
The following Sass will do the trick:
button,
input[type="reset"],
input[type="button"],
input[type="submit"],
input[type="file"] > input[type="button"]
&::-moz-focus-inner
border: none
There's also a plain CSS version.
Note that you can no longer visually navigate through a form with the keyboard without these borders.
Papertrail - Store each models version in a separate table
Store each models version in a separate table
class Post < ActiveRecord::Base
has_paper_trail :class_name => 'PostVersion'
end
class PostVersion < Version
# custom behaviour, e.g:
set_table_name :post_versions
end
Collection of Rails development boosting frameworks
Development environment setup
- Rails Composer
-
Basically a comprehensive Rails Template. Prepares your development environment and lets you select web server, template engine, unit and integration testing frameworks and more.
Generate an app in minutes using an application template. With all the options you want!
Code generators
- Rails Bricks
-
A command line wizard. Once you get it running, it creates sleek applications.
RailsBricks enables you to cre...
Bash: Heavy headings for CLI
To print a colored full-width bar on the bash, use this bash script expression:
echo -e '\033[37;44m\nHEADING\033[0m\nLorem ipsum ...'
In Ruby:
puts "\033[37;44m\n #{text}\033[0m" # blue bar
Notes: -e
turns on escape character interpretation for echo
. See this card for details on bash formatting.
The line above will print:
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.
How to force a client-side refresh on a new favicon
Browsers usually cache favicons. If you update the favicon of your web site and want all visitors to see the new icon, you need to give the icon a different URL. You will not have this issue if you cache your assets properly, which appends a fingerprint to your image URL (like favicon.ico?432423432
):
<link href="<%= image_path('favicon.ico') %>" rel="icon" type="image/vnd.microsoft.icon">
String#indent: Know your definitions!
String#indent
is not a standard Ruby method. When you use it, be sure to know where this method comes from. Many Gems shamelessly define this method for internal usage, and you'll never know when it may be removed (since it's usually not part of the Gem's API).
Unless you're using Rails 4 (which brings String#indent
in ActiveSupport), you'll be best of defining it yourself. This card has it for you.
Gems that define String#indent
(incomplete)
----------------------------...
Spreewald version 0.9.4 released
- "I click on ..." step fixed
- Errors added to
ToleranceForSeleniumSyncIssues::RETRY_ERRORS
Capybara::ElementNotFound
Selenium::WebDriver::Error::ElementNotVisibleError
Selenium::WebDriver::Error::NoSuchFrameError
Fix when assigning nested attributes raises "undefined method `to_sym' for nil:NilClass"
You might have a table without a primary key set in MySQL.
You can fix this by adding a primary key index to the guilty MySQL table, or by setting self.primary_key = "id"
in your class definition.
Related, but different issue: Rails 2 does not find an association when it is named with a string instead of a symbol
Debugging in Cucumber
Spreewald includes a few useful steps for debugging a Capybara session.
Then show me the page # => Opens the page in the browser
Then debugger # => Open a debugging session
Unicode support in MySQL is ...
For reasons that completely escape me, MySQL 5.x limits UTF-8 strings to U+FFFF and smaller.
Cucumber does not find neither env.rb nor step definitions when running features in nested directories
Usually, Cucumber feature files live in features/
. When you group them in sub directories, make sure to add -r features
to the standard Cucumber options.
In Rails apps, Cucumber options are likely to be stored in config/cucumber.yml
.
Cucumber: Wait until CKEditor is loaded
I had to deal with JavaScript Undefined Error
while accessing a specific CKEditor instance to fill in text.
Ensure everything is loaded with
patiently do
page.execute_script("return isCkeditorLoaded('#{selector}');").should be_true
end
Example
The fill in text
snippet for Cucumber:
When /^I fill in the "([^\"]+)" WYSIWYG editor with:$/ do |selector, html|
patiently do
page.execute_script("return isCkeditorLoaded('#{selector}');").should be_true
end
html.gsub!(/\n+/, "") # otherwise: unterminated string lit...
Using Arel to Compose SQL Queries
Arel is a library that was introduced in Rails 3 for use in constructing SQL queries. Every time you pass a hash to where, it goes through Arel eventually. Rails exposes this with a public API that we can hook into when we need to build a more complex query.
Namespacing: why `uninitialized constant` error may occour in `development` but not in `test` environment
Example:
class Book::Page
end
class MyBook < Book
def new_page
Page.new # has to be `Book::Page` in development to make it work
end
end
Method new_page
may throw an error when it was called during browser interaction in development but doesn't make the test fail.
The reason
Development autoloading isn't smart enough to find the referenced class
At other environments (test, staging, production) autoloading is disabled, that all classes are already loaded when browser interaction takes place what makes...
Howto prompt before accidentally discarding unsaved changes with JavaScript
Ask before leaving an unsaved CKEditor
Vanilla JavaScript way, but removes any other onbeforeunload
handlers:
$(function(){
document.body.onbeforeunload = function() {
for(editorName in CKEDITOR.instances) {
if (CKEDITOR.instances[editorName].checkDirty()) {
return "Unsaved changes present!"
}
}
}
}
A robuster implementation example
Note: Don't forget to mark the 'search as you type' forms with the skip_pending_changes_warning
class.
var WarnBeforeAccidentallyDiscard...