Run a rake task in all environments
Use like this:
power-rake db:migrate VERSION=20100913132321
By default the environments development
, test
, cucumber
and performance
are considered. The script will not run rake on a production
or staging
environment.
This script is part of our geordi gem on github.
Run a single example group in RSpec
To only run a single describe
/context
block in a long spec, you can say
spec spec/models/note_spec.rb:545
... where the describe
block starts at line 545.
Note: This will only run examples that are direct children of this block, not descendants further down (when nesting describe
/context
blocks).
You may also pass the line of an it
block to run this exact one.
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This is useful if both the hash key and value can be derived from each array element:
users = User.all
user_names_by_id = users.to_h { |user| [user.id, user.name] }
{
1 => "Alice",
2 => "Bob"
}
Array#to_h
on an array of key/value tuples (Ruby 2.1+)
Converts an Array ...
Find files modified since a given timestamp
If you need to find all files inside a directory that were modified in the last 24 hours you can do this:
find . -mtime 1
You can also refer to another file's timestamp like this:
find . -cnewer other_file
This can be used to check against a specific timestamp, too. This is how you check for all files modified today (since 00:00):
touch -t `date +%m%d0000` /tmp/$$
find . -cnewer /tmp/$$
Note that $$
returns the current bash's PID so you will get some file like /tmp/12345 that stays the same for the current shell. This...
Cheating Rails: Calling render() outside your Controllers
Do that for noble reasons only.
Create a valid RSS feed in Rails
This will show you how to create a RSS feed that the Feed Validator considers valid.
Note that RSS is a poorly specified format. Consider using the Atom builder to make an Atom feed instead. Write a note here if you do.
- Controller
Create a FeedsController
to host the RSS feed. Such a controller is also useful to host other data feeds that tend to gather over the lifetime of an application, e.g. sitemap.xml
.:
class...
JQuery CSS Emoticons Plugin
The CSS Emoticons plugin is a simple jQuery plugin (and stylesheet) that allows you to turn any text emoticons on the page into cute little smiling faces with pure CSS3 styling (no images whatsoever).
Rename hash keys
If you want to rename a key of a Ruby hash, this could help you out.
Just put it into something like config/initializers/hash_move.rb
.
Use the new Google Images as a German user
In july Google announced a new version of their image serach tool Google Images. But you won't find it on the German google.de site. To reach the new - as I may say, very much better - tool from germany, you have to surf to images.google.com. Et voilà!
clemens's delocalize at master - GitHub
delocalize provides localized date/time and number parsing functionality for Rails.
Install RubyGems on Ubuntu/Debian
First of all: You could just use RVM which would make the pain go away. If for some reason you can't, proceed.
Do not use rubygems from the apt repository.
- Get the latest RubyGems TGZ
- Change to the download directory and extract it:\
tar xvfz rubygems-1.3.7.tgz
- If you previously had RubyGems installed via apt: \
sudo apt-get remove rubygems
- Install RubyGems:\
cd rubygems-1.3.7 && sudo ruby setup.rb
- Link
gem
togem1.8
:\
`sudo ...
Remove resource fork files from a FAT volume on MacOS
Be careful!
The following solution will delete files on a volume. If you don't know exactly what you're doing, you can run into big trouble with your computer.
I play mp3 files on my car stereo that are stored on a SD-Card.
When I've copied those mp3 files to the FAT formatted SD-Card on my Mac, then I will see those nasty resource fork files (beginning with "._") for every file and folder on my car stereo. In most cases those resource fork files are important and invisible and don't bother you – on my car stereo ...
Understand ActiveRecord::ReadOnlyRecord error
When you load a record with find options that have SQL fragments in :select
or :joins
, ActiveRecord will make that record read-only. This is a protective measure by Rails because such a record might have some additional attributes that don't correspond to actual table columns.
You can override that precaution by appending :readonly => false
to affected find options or scope options.
When sessions, cookies and Clearance tokens expire and how to change it
Expiration of Rails sessions
By default Rails sessions expire when the user closes her browser window.
To change this edit your config/initializers/session_store.rb
like this:
ActionController::Base.session = {
:key => '...',
:secret => '...'
:expire_after => 10.years
}
In older Railses the initializer is not available. Set the option in the environment.rb
instead:
config.action_controller.session = {
:key => '...',
:secret => '...'
...
Flash SWF movie bleeds into an element covering it
Embedded Flash movies do not always obey element order and z-index
.
To fix this, set the wmode
attribute to transparent
in both <object>
and <embed>
tags:
<object ... >
<param name="wmode" value="transparent" />
<embed ... wmode="transparent" />
</object>
Strip carriage returns in submitted textareas
When submitting textarea
s, browsers sometimes include carriage returns (\r
) instead of just line feeds (\n
) at the end of each line. I don't know when this happens, and most of the time it doesn't matter.
In cases where it does matter, use the attached trait to remove carriage returns from one or more attributes like this:
class Note
does 'strip_carriage_returns', :prose, :code
end
Here is the test that goes with it:
describe Note do
describe 'before_validation' do...
Split nested block parameters
If you iterate over a collection of arrays, you can destructure the arrays within the block parameters:
movies_and_directors = [
['The Big Lebowski', 'Coen Brothers'],
['Fight Club', 'David Fincher']
]
movies_and_directors.each do |movie, director|
# do something
end
For nested array (e.g. when you use each_with_index
), you can use parentheses for destructuring:
movies_and_directors.each_with_index do |(movie, director), index|
# do something
end
Fix a spec that only runs when called directly
When a spec only runs when it is called directly, but not as part of the whole test suite, make sure the filename is foo_spec.rb
instead of just foo.rb
.
Using RSpec stubs and mocks in Cucumber
By default, Cucumber uses mocha. This note shows to use RSpec stubs and mocks instead.
Rspec 1 / Rails 2
Put the following into your env.rb
:
require 'spec/stubs/cucumber'
Rspec 2 / Rails 3
Put the following into your env.rb
:
require 'cucumber/rspec/doubles'
Note: Since Cucumber 4 it is important to require these lines in the env.rb
and not any other file in support/*
to register the hooks after any other After
hook in support/*
. Otherwise your doubles are removed, while other After
steps requi...
Enable tab dragging in RubyMine
Since RubyMine 3.1 you can drag tabs across panes/windows and out of the main window to create new windows.
For any version below 3.1 do it like this (will only allow dragging tabs inside their pane, not across panes):
- File → Settings
- Editor → Editor Tabs
- Check "Show tabs in single row"
Seriously.
Fan control for Dell notebooks
sudo apt-get install i8kutils
- Reboot
- You can now run the i8k tools such as
i8kmon
Setting the fan speed to high (2) will only work shortly as the fan is somehow controlled automatically.\
This helps you out in bash:
while true; do i8kfan - 2; sleep 0.2; done
There should be a better solution and it will be posted as soon as it's found.
Install a local Gemfile on a remote server
Call with the server's hostname (and user if you have no SSH agent), e.g.
install-gems-remotely my.server.com
# or without agent:
install-gems-remotely me@my.server.com
When you call it from a rails directory, it uploads your Gemfile
, Gemfile.lock
as well as the gemspecs of all vendored gems in to a temporary folder on the server and does a bundle install
there.
If you need to install gems from anothere Gemfile, just do it like this:
BUNDLE_GEMFILE=Gemfile.something; install-gems-remotely my.server.com
This scri...
wmd - The Wysiwym Markdown Editor
WMD is a simple, lightweight HTML editor for blog comments, forum posts, and basic content management. You can add WMD to any textarea with one line of code. Add live preview with one line more. WMD works in nearly all modern browsers, and is now completely free to use.