Use CSS attribute selectors with Capybara
You can use CSS attribute selectors in your step definitions like this:
Then /^the page should have a meta description "([^"]+)"$/ do |description|
page.should have_css("meta[name=\"description\"][content=\"#{description}\"]")
end
Note that you need to always quote attribute values or you will get a Nokogiri parsing error like this:
unexpected 'foo' after 'equal' (Nokogiri::CSS::SyntaxError)
Collect an array of IDs from any object
The Edge Rider gem will define a method collect_ids
on your ActiveRecord models, scopes, integer scalars and collections, which will return a list of their IDs:
User.last.collect_ids # => [9]
[User.first, User.last].collect_ids # => [1, 9]
User.active.collect_ids # => [4, 5, 6]
[4, 5, 6].collect_ids # => [4, 5, 6]
7.collect_ids #=> [7]
This allows you to parametrize scopes with a variety of argument types:
class Note < ActiveRecord::Base
named_scope :for_users, lamb...
Fix "undefined method `destroy'" in reset_session
This is a bug in Rails 2.3.11 which will be fixed in a future maintenance release.
Until then you can copy the attached initializer to config/initializers
.
makandra/consul
Our new scope-based authorization gem for Ruby on Rails has been released. This might one day replace Aegis as our standard authorization solution.
List your current Git remotes
To display a list of your current Git remotes and their endpoints, you can say
git remote -v
The output looks like this:
brady8 https://github.com/brady8/aegis.git (fetch)
brady8 https://github.com/brady8/aegis.git (push)
origin git@github.com:makandra/aegis.git (fetch)
origin git@github.com:makandra/aegis.git (push)
Convert RDoc markup to HTML
If you want to convert a README.rdoc
file to HTML, say this from a shell:
rdoc README.rdoc
You will find the generated HTML in doc/index.html
.
If you do this while working on one of our gems, please .gitignore
everything in doc
and don't commit the generated HTML.
Why preloading associations "randomly" uses joined tables or multiple queries
ActiveRecord gives you the :include
option to load records and their associations in a fixed number of queries. This is called preloading or eager loading associations. By preloading associations you can prevent the n+1 query problem that slows down a many index view.
You might have noticed that using :include
randomly seems to do one of the following:
- Execute one query per involved table with a condit...
jeanmartin/konto_check
Ruby gem to check whether a given bic/account-no-combination can possibly be valid for a German bank. Can also resolve German bank names from a given bic.
Use non-ASCII characters on IRB and Rails consoles with RVM and Mac OS X
If you are using RVM on a Mac and cannot enter 8+ bit characters on an IRB or Rails console, you are missing the readline
package. You will need to re-install your Ruby to fix this:
rvm remove ree
rvm package install readline
rvm install ree --with-readline-dir=$rvm_path/usr
rvm default ree
Substitute ree
with the name if your Ruby distribution.
This note was contributed by Matthias Marschall from the Agile Web Development & Operations blog.
Cast a string to the type of an ActiveRecord attribute
ActiveRecord models know how to cast a given string to the type of a given attribute (or column).
The following model will serve as our example:
create_table :notes do |t|
t.string :title
t.integer :user_id
t.boolean :deleted
end
You can make the Note
class cast strings into their respective types like this:
Note.columns_hash['user_id'].type_cast('123') # => 123
Note.columns_hash['deleted'].type_cast('1') # => true
Note.columns_hash['deleted'].type_cast('0') # => false
Retrieve the SQL query a scope would produce in ActiveRecord
Rails 3
User.active.to_sql
Rails 2
Use either the Edge Rider or fake_arel gem to get #to_sql
backported to Rails 2.
If you don't want to use a gem for this, you can do this with vanilla Rails 2:
User.active.construct_finder_sql({})
How to perform HTTP basic authentication in RSpec
The Basic Authentication header encodes username and password. Effectively, it's just Base64 plus a "Basic
" prefix.
You can use ActionController::HttpAuthentication::Basic.encode_credentials
for that, and put its result into the Authorization
request header.
Request specs
For request specs, use the :header
option.
it 'requires authentication' do
get '/'
expect(response.status).to eq(401)
end
it 'accepts valid credentials' do
encoded_credentials = ActionController::HttpAuthentication::Basic.encode_credentials(use...
Debian/Ubuntu: See what "apt" would install without actually doing it
Simply add --dry-run
, like this:
sudo apt-get install --dry-run something
This is great if packages would get updated and you want to easily see which version they will receive.
Installing RubyGems for Ruby 1.8.6
Since version 1.5 RubyGems requires at least Ruby 1.8.7. The last one working with Ruby 1.8.6 was RubyGems 1.4.2.
You get still download it from their servers and install RubyGems.
Dropbox + git = Designer <3
One of the thornier problems in our workflow is knowing when assets are delivered from the designer and keeping them in sync with our application as they change. We used to use e-mail, Skype or sticky notes. The trouble is that the designer's file naming and directory structure were never quite the same as the application's /public/images directory, so direct comparisons were impossible and we ended with a lot bookkeeping to make sure that we didn't lose any changes. Our solution is to clone the project's git repository into a folder inside ...
Open the on-screen keyboard on an iPhone or iPad with Javascript
There is no way to do it. This behavior is by design. You lose.
Installing RMagick on Ubuntu
When installing RMagick you may get an error messages like this:
Version 2.13.1:
checking for Ruby version >= 1.8.5... yes
checking for gcc... yes
checking for Magick-config... no
Can't install RMagick 2.13.1. Can't find Magick-config in /home/arne/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/var/lib/gems/1.8/bin
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
d...
Opera: How to use outlining for better layout debugging
I prefer using Opera's "User mode" to toggle an outlining of HTML elements quickly. This helps greatly when you want to see the actual dimensions of elements, e.g. for floating elements inside containers, instead of opening up the Dragonfly inspector every time.
Navigate to View → Style → "Manage Modes..." and tick the checkboxes like in the attached image. Then, switch to the User Mode by pressing the shortcut (Shift+G for the 9.2-compatible layout or for the default layout with enabled "single-key shortcuts") and select "Outline" from...
Opera 11: Show full address, including GET parameters
By default, Opera 11 hides any passed params and the URL's protocol until you focus the address bar.
To disable hiding URL parameters, open up Tools → Preferences (Ctrl+F12) → Advanced → Browsing and check "Show full web address in address field". No need to touch opera:config.
The badge that displays the page's "zone" (Web, Secure, Opera, ...) will be shrinked so you can still see a yellow lock for proper SSL connections, etc.
Default views in Rails 3.0 with custom resolvers
It is common in Rails 3.0 applications that you want to provide default views for a group of controllers. Let’s say you have a bunch of controllers inside the Admin namespace and you would like each action to fallback to a default template. So if you are rendering the index action for Admin::PostsController and “app/views/admin/posts/index.html.*” is not available, it should then render “app/views/admin/defaults/index.html”.
Since Rails 3.0, we have a new abstraction called resolvers that holds the logic to find a template.
How to send a test e-mail from shell
If you want to manually check if e-mail delivery works on a machine by sending an e-mail you can run the following:
mail -s Test someone@example.com < /dev/null
This will send an empty e-mail with "Test" as its subject to someone@example.com
.
If you want it to contain a message body, call mail -s Test someone@example.com
only; the mail
application will then read your input from stdin. Finish your message by sending EOT with Ctrl-D -- if you are asked for anything else ...
Cast an ActiveRecord to a subclass or superclass
Note: ActiveRecord::Base#becomes
has a lot of quirks and inconsistent behavior. You probably want to use ActiveType.cast
instead.
ActiveRecord models have with a method becomes(klass)
which you can use to cast the record into an instance of its subclasses or superclass. This is useful because some parts of Rails reflect on the class of an instance, e....