Rails jQuery UJS: Now Interactive
We can now plug into every facet of the Rails jQuery UJS adapter, binding to custom events, and even customizing internal functions, without hacking or monkey-patching the rails.js file itself.
Saving application objects in your session will come back to haunt you
If you save a non-standard object (not a String or Fixnum, etc) like the AwesomeClass
from your application in the session of visitors be prepared that some time you will get this exception:
ActionController::SessionRestoreError: Session contains objects whose class definition isn't available. Remember to require the classes for all objects kept in the session. (Original exception: ...)
This happens when you remove your AwesomeClass
but users come back to your site and still have the serialization of such objects in their session....
How to: Apache logs on a daily basis without logrotate
If you want to have a new log file every day automatically, but avoid using logrotate
, the CustomLog
directive is your friend:
CustomLog "|/usr/sbin/rotatelogs /opt/www/awesome-project/log/access.%Y-%m-%d.log 86400" combined
Adding that to your site's vhost will create log files that include the current date in their name, like access.2011-04-20.log
, without any need to restart the web server every night (like logrotate
does).
The last argument above is the rotation time in seconds -- here being 86400 (= 60 * 60 * 24) which ca...
How to fix strangely disappearing or misbehaving forms
You most likely have a form
element inside another form
element. Don't do that. Ever.
Firefox and Chrome will discard the first form
nested inside another form
(but for some reason keep others). Internet Explorer will possibly act like nothing is wrong -- but break (send the outer form) when you submit.
If your application behaves normal at first but removes forms from the DOM when you Ajax around, this could be the cause. Remember this note when you think your browsers are broken once again and check for such things thoroughly bef...
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...