How Rails and MySQL are handling time zones
When working with times and dates in Rails applications, you need to deal with the following problem:
- In Rails,
Timeobjects have a time zone. You can get the zone name by doingtime_object.zone. - This zone is considered when doing time calculations, e.g. 10 AM CEST minus 8 AM UTC is zero.
- A datetime in MySQL does not have a zone. It just stores the literal string "2010-05-01 12:00:00".
- That means that Rails must make assumptions about timestamps loaded from and written to MySQL.
Rails has two completely different modes ...
Regular Expressions - Cheat Sheet
You can write regular expressions some different ways, e.g. /regex/ and %r{regex}. For examples, look here.
Remember that it is always a good idea to match a regex visually first.
Characters
Literal Characters
[ ] \ ^ $ . | ? * + ( )
Character Classes
[ae] matches a and e, e.g. gr[ae]y => grey or gray => but NOT graay or graey
[0-9] ...
Run a POP3 server on a directory of mail files with popthis
popthis is awesome when used with inaction_mailer.
Install the gem:
sudo gem install popthis
Start the server:
popthis tmp/sent_mails/ # e.g. the folder containing the .txt-mails generated by inaction_mailer
Now, configure your mail client as follows:
Server: localhost
Protocol: POP3
Port: 2220
Username: anything
Password: anything
Marry Capybara with SSL-enabled applications
Capybara does not play nice with sites that have some actions protected by SSL, some not. A popular way to implement this in Rails is using the ssl_requirement plugin by DHH, which redirects a requests from HTTP to HTTPS if the requested action requires SSL and vice versa.
Capybara follows the redirect, but seems to forget the changed protocol for the next request. The only hack-free workaround right now is to use URLs in lieu of paths everywhere (links, form actions).
For a hackful fi...
rspec_candy is now a gem
Our awesome collection of rspec helpers (formerly known as "spec_candy.rb") is now available as a gem. It works, it is tested and there will be updates.
Usage
Add rspec_candy to your Gemfile.
Add require 'rspec_candy/helpers' to your spec_helper.rb, after the rspec requires.
List of features
Announcing YARD 0.6.0 (gnuu.org)
YARD 0.6 adds the ability to serve documentation for gems as well as the current project with yard server. Just like gem server in RubyGems, you can serve gem docs. The advantage to YARD’s server is that you don’t need to pre-generate the static docs (with a gem install) before running the server. If you installed your gem with --no-rdoc, YARD will just generate it on the fly!
Ruby Reports
Ruport’s acts_as_reportable module provides support for using ActiveRecord for data collection. You can use it to get a Ruport::Data::Table from an ActiveRecord model. This cheatsheet covers the basic functionality of acts_as_reportable and some common use cases.
Build a JSON API for a Rails application
Try our Apify gem which solves many problems you will be having.
jeremyevans's home_run at master - GitHub
home_run is an implementation of ruby’s Date/DateTime classes in C, with much better performance (20-200x) than the version in the standard library, while being almost completely compatible.
Error installing the raspell gem
When you get this while installing the raspell gem:
ERROR: Error installing raspell:
ERROR: Failed to build gem native extension.
You need some libraries:
sudo apt-get install libaspell-dev
Aspell Error - No word lists can be found for the language XY
When you get this error:
No word lists can be found for the language "de".
An aspell dictionary is missing. Install it with
sudo apt-get install aspell-de
stefankroes's ancestry at master - GitHub
Ancestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single sql query. Additional features are STI support, named_scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrit...
Release gem; Deploy gem; Update a gem created with Jeweler
Until May 2011 our gems have been created with Jeweler, which is a helper library to package code into a gem. You know a gem was cut with Jeweler if you see the word jeweler in a gem project's Rakefile.
This note describes how to update a gem that was cut using Jeweler. Note that this can be traumatic the first time. It would be great to have an easier workflow for this. Jeweler is deprecated these days because you can
**now [cut gems more easily using Bundler](https://makandracards.com/makandra/1229-updat...
Better output for Cucumber
We built cucumber_spinner to have a progress bar for Cucumber features, which also outputs failing scenarios as soon as they fail.
Installation
gem install cucumber_spinner
Usage
cucumber --format CucumberSpinner::ProgressBarFormatter
If you use CucumberSpinner::CuriousProgressBarFormatter and a feature fails, the according page will show up in your browser.
Note that if you run your Cucumber tests using the [cuc](https://makandracards.com/makandra/1277-a-nicer-way-to-...
Test concurrent Ruby code
To test concurrent code, you will need to run multiple threads. Unfortunately, when you use blocking system calls (e.g. locks on the database), Ruby 1.8 threads won't work because system calls will block the whole interpreter.
Luckily you can use processes instead. fork spins off a new process, IO.pipe sends messages between processes, Process.exit! kills the current process. You will need to take care of ActiveRecord database connections.
Here is a full-fledged example:
describe Lock, '.acquire' do
before :each do
...
Better Output for RSpec
rspec_spinner is a progress bar for RSpec which outputs failing examples as they happen (instead of all at the end).
Installation
gem install rspec_spinner
Usage
script/spec -r rspec_spinner -f RspecSpinner::Bar -c
To make a shortcut in your .bashrc
alias ss='script/spec -r rspec_spinner -f RspecSpinner::Bar -c'
There's also an alternate runner RSpecSpinner::Spinner which shows a spinner and the name of the current spec instead of a progress bar.
Concurrent Tests
Install gem and plugin
sudo gem install parallel
script/plugin install git://github.com/grosser/parallel_tests.git
Adapt config/database.yml
test:
database: xxx_test<%= ENV['TEST_ENV_NUMBER'] %>
Create test databases
script/dbconsole -p
CREATE DATABASE `xxx_test2`;
...
Generate RSpec files
script/generate rspec
(you'll probably only let it overwrite files in script/)
Prepare test databases...
Parse XML or HTML with Nokogiri
To parse XML-documents, I recommend the gem nokogiri.
A few hints:
-
xml = Nokogiri::XML("<list><item>foo</item><item>bar</item></list>")parses an xml string. You can also callNokogiri::HTMLto be more liberal about accepting invalid XML. -
xml / 'list item'returns all matching nodes;list itemis used like a CSS selector -
xml / './/list/item'also returns all matching nodes, but.//list/itemis now an XPath selector- XPath seems to be triggered by a leading
....
- XPath seems to be triggered by a leading
Rails - Multi Language with Fast_Gettext
sudo gem install gettext --no-ri --no-rdocsudo gem install fast_gettext --no-ri --no-rdoc-
script/plugin install git://github.com/grosser/gettext_i18n_rails.git(didn't work as gem) - environment.rb: see code example at the bottom
-
if this is your first translation:
cp locale/app.pot locale/de/app.pofor every locale you want to use - use method "_" like
_('text')in your rails code - run
rake gettext:findto let GetText find all translations used - translate messages in 'locale/de/app.po' (leave msgstr blank and ms...
Automatically build sprites with Lemonade
How it works
See the lemonade descriptions.
Unfortunately, the gem has a few problems:
- it does not work with Sass2
- it always generates all sprites when the sass file changes, which is too slow for big projects
- it expects a folder structure quite different to our usual
All these problems are solved for us, in our own lemonade fork. This fork has since been merged to the original gem, maybe we can use t...
Using Passenger for development (with optional SSL)
- install apache
sudo apt-get install ruby1.8-devsudo gem install passengersudo passenger-install-apache2-module- follow the instructions
Manually: configure a vhost in /etc/apache2/sites-available and link it to /etc/apache2/sites-enabled with something like the following
^
NameVirtualHost *:80
<VirtualHost *:80>
ServerName application.local
DocumentRoot /opt/application/public
RailsEnv development
RailsAllowModRewrite off
</VirtualHost>
<VirtualH...
Freeze (vendor, unpack) a single Ruby gem with and without Bundler
When you need to patch an existing gem, one way is to "vendor" the gem by copying it into the vendor/gems directory of your Rails project. You can then make any changes you require and Rails will use the vendored version of the gem after a server restart. Unfortunately you need to perform some additional steps to marry Rails and the copied gem. This notes describes what to do.
With Bundler
This is super-painful. If you just copy the gem to vendor/gems, Rails will complain:
Unpacked gem foolib in vendor/gems has no s...