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...
Testing state_machine callbacks without touching the database
You should test the callback methods and its correct invocation in two separate tests. Understand the ActiveRecord note before you move on with this note.
Say this is your Spaceship
class with a transition launch
and a release_docking_clamps
callback:
class Spaceship
state_machine :state, :initial => :docked do
event :launch do
transition :docked => :en_route
end
before_transition :on => :launch, :do => :release_doc...
The dangers of url_for in Rails applications
In a great post about named routes in Rails, path vs. url, Viget Labs ponders which variant is best used.<br />
<br />
Most often we use foo_path, which when used in Rails URL helpers will generate a relative path, where foo_url generates a full URL. In most cases the path makes most sense, but not always.
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.
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 => '...'
...
Embed a favicon properly
The following Haml will do:
%head{ :profile => 'http://www.w3.org/2005/10/profile' }
%link{ :href => image_path('favicon.ico'), :rel => 'icon', :type => 'image/vnd.microsoft.icon' }
Note that while you can link to icon formats other than .ico
, Internet Explorer is too stupid for that.
Know your Haml comments
There are two distinct ways of commenting Haml markup: HTML and Ruby.
HTML comments
This will create an HTML comment that will be sent to the client (aka browser):
/= link_to 'Example', 'www.example.com'
This produces the following HTML:
<!-- = link_to 'Example', 'www.example.com' -->
Only use this variant if you need the comment to appear in the HTML.
Ruby comments
This will comment code so it will not be sent to the client:
-# = link_to 'foo'
99% of the time you'll be adding notes f...
Difference between respond_to/format and params[:format]
To return non-HTML responses (like XLS spreadsheets), we usually use the
respond_to do |format|
format.xls do
# send spreadsheet
end
end
This is often, but not always the same as checking for params[:format] == :xls
, so don't rely on this when e.g. one format checks for authorization and the other doesn't.
params[:format]
is only set when a user explicitly puts a .xls
at the end of the URL.
The format.xls
block also responds when the user's browser requests the application/excel
MIME type.
If Internet Explo...
Bundler for Rails 2.3.x
Update RubyGems and Passenger
Bundler requires Rubygems >= 1.3.6. Run gem update --system
if you have an older version.
It also is not compatible with older versions of passenger, so bring that up to date as well (2.2.15 works).
If you installed RubyGems through apt (which you should never do!), you may see a message giving you a hint to use apt to update.
Some people advise to install the 'rubygems-update-1.3.7' gem on Ubuntu systems if you used apt to install RubyGems.
I did that - and lost all...
Recursively remove unnecessary executable-flags
Sometimes files attain executable-flags that they do not need, e.g. when your Windows VM copies them over a Samba share onto your machine.
From inside your Rails project directory call regularly:
geordi remove-executable-flags
Runs chmod -x
on Ruby, HTML, CSS, image, Rake and similar files.
This script is part of our geordi gem on github.
Unobtrusive jQuery to toggle visibility with selects and checkboxes
Use this if you want to show or hide part of a form if certain options are selected or boxes are checked.
The triggering input gets an data-selects-visibility
attribute with a selector for the elements to show or hide, like
<%= form.select :advancedness, [['basic', 'basic'], ['advanced', 'advanced'], ['very advanced', 'very_advanced]], {}, :"data-selects-visibility" => ".sub_form" %>
The elements that are shown/hidden look like
<div class="sub_form" data-show-for="basic">
only shown for advancedness = basic
</div>
...
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] ...
Default implementation of resource_controller actions
jamesgolick / resource_controller at Github
module ResourceController
module Actions
def index
load_collection
before :index
response_for :index
end
def show
load_object
before :show
response_for :show
rescue ActiveRecord::RecordNotFound
response_for :show_fails
end
def create
build_o...
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
Submit a form with Prototype
For example, to send a form and populate a preview div with the response.
$('content_form').request({
parameters: { 'preview': "1" }, // overrides parameters
onComplete: function(transport){
$('previewContent').update(transport.responseText);
}
});
Autofocus a form field with HTML5 or jQuery
In Webkit you can use the HTML5-attribute autofocus
:
= form.text_field :title, :autofocus => 'autofocus'
Here is a jQuery fallback for browsers that don't speak HTML5:
var Autofocus = {
supported: function() {
return 'autofocus' in document.createElement('input');
},
fake: function() {
$('[autofocus]').focus();
},
extend: function() {
Autofocus.supported() || Autofocus.fake();
}
};
$(Autofocus.extend);
Cucumber Webrat steps
Most of these will not work in newer projects because these use the Capybara/Rack::Test combo in lieu of Webrat.
Find input fields
Then /^there should be a "([^"]+)" field$/ do |name|
lambda { webrat.current_scope.send(:locate_field, name) }.should_not raise_error(Webrat::NotFoundError)
end
Then /^there should be no "([^"]+)" field$/ do |name|
lambda { webrat.current_scope.send(:locate_field, name) }.should raise_error(Webrat::NotFoundError)
end
Find html content
Then /^I should see "([^\"]*)...
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...
Aggregated RSpec/Cucumber test coverage with RCov
With defaults, RCov doesn't work the way you how you would like it to. To create a nice test coverage report, copy the attached file to lib/tasks/rcov.rake
. After that rake rcov:all
will run all RSpec examples and Cucumber features. The report will be written RAILS_ROOT/coverage/index.html
.
Here is what the task does in detail:
- Generates aggregated coverage of both RSpec and Cucumber
- Works with Rails 2 and Rails 3
- Reports for
app/**/*.rb
and nothing else - If called with an environment variable
IGNORE_SHARED_TRAITS=true
it ...
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::HTML
to be more liberal about accepting invalid XML. -
xml / 'list item'
returns all matching nodes;list item
is used like a CSS selector -
xml / './/list/item'
also returns all matching nodes, but.//list/item
is now an XPath selector- XPath seems to be triggered by a leading
.
...
- XPath seems to be triggered by a leading
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...
Convert Haml to ERB
This is about converting Haml to ERB and not the other way round which you probably want!
This process can not be automated 100%, but you can still save time.
First do
script/plugin install http://github.com/cgoddard/haml2erb.git
Then in the console type
hamls = Dir["app/views/**/*.haml"] - ['app/views/layouts/screen.html.haml'];
hamls.each do |haml|
puts haml
erb = haml.sub(/\.haml$/, '.erb')
File.open(erb, 'w') do |file|
file.write Haml2Erb.convert(File.read(haml))
end
end
After th...