Note that this card is very old. You might want to use ActiveType for your auto-coerced virtual attributes instead.
We sometimes give our models virtual attributes for values that don't need to be stored permanently.
When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that...
E.g. when you're using a tagging gem, you have seen virtual attributes that get and set a string array:
post = Post.last
puts post.tag_list # ['foo', 'bar', 'baz']
post.tag_list = ['bam']
puts post.tag_list # ['bam']
If you would like to create a form displaying one check box per tag, you can do this:
- form_for @post do |form|
= form.check_box :tag_list, { :multiple => true }, 'foo', nil
= form.check_box :tag_list, { :multiple => true }, 'bar', nil
=...
This step tests whether a given select option comes preselected in the HTML. There is another step to test that an option is available at all.
Then /^"([^"]*)" should be selected for "([^"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector|
with_scope(selector) do
field_labeled(field).find(:xpath, ".//option[@selected = 'selected'][text() = '#{value}']").should be_present
end
end
Webrat
...
This collection of Sass mixins enables cross-browser styling (including IE with CSS3PIE) with less lines of code.
This enables PIE for IE up to version 8 only (the first part is not possible in Haml, so use ERB):
<!--[if !IE]><!-->
<%= stylesheet_link_tag 'screen', :media => 'screen' %>
<!--<![endif]-->
<!--[if lte IE 8]>
<%= stylesheet_link_tag 'screen_with_pie', :media => 'screen' %>
<![endif]-->
These would be your two screen Sasses:
# screen_with_pie.sass
...
There is a problem with AJAX response handling for Rails 3 remote links and forms in Internet Explorer. This problem affects applications still using jQuery 1.4.2.
The following initializer provides an :alias => "my_route_name"
option to restful routes in your route.rb
. This simply makes the same route also available under a different ..._path / ..._url helpers.
For example,
map.resources :notes, :alias => :snippets
Gives you
notes_path, notes_url, new_note_path... #as always
snippets_path, snippets_url, new_snippet_path... #from the alias
Put this into an initializer:
Regular spaces and non-breaking spaces are hard to distinguish for a human.
Instead of using the
HTML entity or code like " " # this is an nbsp
, use a well-named helper method instead.
def nbsp
[160].pack('U*')
end
160 is the ASCII character code of a non-breaking space.
Thanks to habits engrained by Rails 2’s link_to_remote and remote_form_for, we expect that Rails 3 would also handle the AJAX response for our remote links and forms. But it doesn’t; it leaves that for you.
If a controller action responds to other formats than HTML (XML, PDF, Excel, JSON, ...), you can reach that code in a controller spec like this:
describe UsersController do
describe '#index' do
it 'should be able to send an excel file' do
# stubs and expectations go here
get :index, :format => 'xls'
end
end
end
Remember that both the :format
parameter and the HTTP_ACCEPT
header can m...
This returns the name (including path) of your current layout:
response.layout
=> "layouts/admin" # inside views that are using the 'admin' layout
You most likely do not need the full path, so go ahead and do this:
File.basename(response.layout)
=> "admin"
In rare cases you might need something like form_for
(for using form builder methods on the resulting block element) but without the surrounding form. One such case would be updating some of a form's fields via XHR.
You can simply use Rails' fields_for
to do things like this in your views (HAML here):
- fields_for @user do |form|
= form.label :email, 'E-Mail'
= form.text_field :email
You will only receive the form content you gave, no hidden inputs incl...
When using form_for
you can give the form's target URL either as a string or an array:
form_for(admin_user_path(@user)) do ... end
# same as:
form_for([:admin, @user]) do ... end
Same for link_to:
link_to("Label", edit_admin_user_path(@user))
# same as
link_to("Label", [:edit, :admin, @user])
polymorphic_path
and polymorphic_url
If you would like to generate a path or URL string from an array of route components just as form_for
does, you can use polymorphic_path
or polymorphic_url
:
polymorphic...
Sometimes the order in which strings appear on a page matters to you.
Spreewald gives you steps like these:
Then I should see in this order:
| Alpha Group |
| Augsburg |
| Berlin |
| Beta Group |
Or, if you prefer multiline strings:
Then I should see in this order:
"""
Alpha Group
Augsburg
Berlin
Beta Group
"""
The step ignores all HTML tags and only tests on plain text.
If you have several submit elements (input
s or button
s with type="submit"
) that each cause different things to happen (e.g. you might have a button that sends an extra attribute) you might run into trouble when submitting the form by pressing the return key in a field.
When nothing fancy like a tabindex
is defined it seems as if the first submit element inside a form is chosen (and has its attributes submitted) when pressing return.\
So, if possible, put your "default" (aka least harmful) submit element before others.
NB: If you s...
/etc/crontab
/etc/cron.d/*
/etc/cron.hourly/*
/etc/cron.daily/*
/etc/cron.weekly/*
/etc/cron.monthly/*
crontab -l
and edit with crontab -e
. You'll need to su
to the respective user to view or edit her crontab.You don't need a Rails application to use Sass. Even when you're working on a static site you can generate your CSS through Sass.
sudo gem install haml
sass
in the folder, that stores your stylesheets, e.g. mkdir css/sass
sass --watch css/sass:css
. This will watch your sass files for changes and rewrite stylesheets as required.This even works on Windows.
You might want to change our [typical .gitignor...
For some reason you want to define a find condition in array form. And in that condition both column name and value are coming from user input and need to be sanitized.
Unfortunately this works in SQLite but does not in MySQL:
named_scope :filter, lambda { |attribute, value|
{ :conditions => [ 'articles.? = ?', attribute, value ] }
}
The solution is to use [sanitize_sql_array](http://apidock.com/rails/ActiveRecord/Base/sa...
When using virtual attributes, the attached trait can be useful to automatically copy errors from one attribute to another.
Here is a typical use case where Paperclip creates a virtual attribute :attachment
, but there are validations on both :attachment
and :attachment_file_name
. If the form has a file picker on :attachment
, you would like to highlight it with errors from any attribute:
class Note < ActiveRecord::Base
has_attached_file :attachment
validates_attachment_presence :a...
When Paperclip attachments should only be downloadable for selected users, there are three ways to go.
The same applies to files in Carrierwave.
The first way is to store Paperclip attachments not in the default public/system
, but in a private path like storage
inside the current release. You should prefer this method when dealing with sensitive data.
Make ...
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.
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...
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...
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 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.
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 => '...'
...