How to fix gsub on SafeBuffer objects
If you have an html_safe
string, you won't be able to call gsub
with a block and match reference variables like $1
. They will be nil
inside the block where you define replacements (as you already know).
This issue applies to both Rails 2 (with rails_xss
) as well as Rails 3 applications.
Here is a fix to SafeBuffer#gsub
. Note that it will only fix the $1
behavior, not give you a safe string in the end (see below).
Example
def test(input)...
MySQL: Can I speed up LIKE queries by adding an index?
For string columns, MySQL indexes the left side of a string. That means an index can speed a like query that has a wildcard on the right side:
SELECT * FROM foo WHERE field LIKE "bar%" # will be faster with an index
It can not speed up a query that has a variable left side:
SELECT * FROM foo WHERE field LIKE "%bar%" # will not be faster with an index
That also means if you use the ancestry gem you should index your ancestry
column if you use scopes like descendants
or `su...
Mock the browser time or time zone in Selenium features
In Selenium features the server and client are running in separate processes. Therefore, when mocking time with a tool like Timecop, the browser controlled by Selenium will still see the unmocked system time.
timemachine.js allows you to mock the client's time by monkey-patching into Javascript core classes. We use timemachine.js in combination with the Timecop gem to synchronize the local browser time to the ...
Silencing Your Staging Environment - The Hashrocket Blog
Testing with real live production data does come with at least one catch. All those real live users in your production environment have real live email addresses that receive real live emails.
The post includes monkey patch for ActionMailer that rewrites the domain of all recipients. It's a different take on the problem than our own mail_magnet gem.
Fix error: Missing the mysql2 gem
So you got this error, even though your Gemfile bundles mysql2
:
!!! Missing the mysql2 gem. Add it to your Gemfile: gem 'mysql2'
or
Please install the mysql adapter: `gem install activerecord-mysql-adapter` (mysql is not part of the bundle. Add it to Gemfile.)
The reason for this confusing error message is probably that your Gemfile says mysql2
, but your database.yml
still uses the mysql
adapter. Change it to use the mysql2
adapter:
development:
adapter: mysql2
database: myproject_developm...
rspec_candy 0.2.0 now comes with our most popular matchers
Our rspec_candy gem now gives you three matchers:
be_same_number_as
Tests if the given number is the "same" as the receiving number, regardless of whether you're comparing Fixnums
(integers), Floats
and BigDecimals
:
100.should be_same_number_as(100.0)
50.4.should be_same_number_as(BigDecimal('50.4'))
Note that "same" means "same for your purposes". Internally the matcher compares normalized results of #to_s
.
be_same_second_as
...
Gem development: When your specs don't see dependencies from your Gemfile
When you develop a gem and you have a Gemfile
in your project directory, you might be surprised that your gem dependencies aren't already required in your specs. Here is some info that should help you out:
- Bundler actually doesn't automatically require anything. You need to call
Bundler.require(:default, :your_custom_group1, ...)
for that. The reason why you never had to write this line is that Rails does this for you when it boots the environment. - That also means that if you have an embedded Rails app in your
spec
folder (like [h...
Use the "paper_trail" gem to track versions of records
paper_trail
is an excellent gem to track record versions and changes.
You almost never want to reimplement something like it yourself. If you need to log some extra information, you can add them on top.
It comes with a really good README file that holds lots of examples. I'll show you only some of its features here:
-
- Setting up a model to track changes
- Just add
has_paper_trail
to it:
class User < ActiveRecord::Base
has_paper_trail
end
-
- Accessing a previous version
- Saying
user.previous_version
gi...
How to change will_paginate's "per_page" in Cucumber features
The will_paginate
gem will show a default of 30 records per page.
If you want to test pagination in a Cucumber feature, you don't want to create 31 records just for that.
Instead, you probably want to modify the number of items shown, by saying something like this:
Given we paginate after 2 users
Using the following step definition, you now can! :)
require 'cucumber/rspec/doubles'
Given /^paginate after (\d+) (.*)$/ do |per_page, model_name|
model = model_name.singularize.gsub(/...
When connecting to a second database, take care not to overwrite existing connections
Sometimes, you may want to open up a second database connection, to a read slave or another database. When doing that, you must make sure you don't overwrite an existing connection.
The problem
While this may look good, it will actually cause all kinds of trouble:
def with_other_database
ActiveRecord::Base.establish_connection(slave_settings)
yield
ensure
ActiveRecord::Base.establish_connection(master_settings)
end
Putting aside that you are setting the general connection here (not generally a ...
Drag'n'drop in trees: I went to town
For my Gem Session project Holly I ran the Ironman of drag'n'drop implementations:
- Dragging in nested lists
- User-definable order of items
- Complicated item elements with super-custom CSS and other Javascript functionality
- Items that can be both leaves and containers of other items
- has_ancestry on the server side
Things I learned:
- Be ready to write a lot of CSS. You need to indicate what is being dragged, where it will be dropped, if it is dropped above, below o...
Bundler: Fatal error and 'no such file to load -- net/https'
Today, I ran into trouble on a fairly fresh installed VM, running Ubuntu. I tried to bundle install
and got this stacktrace:
Fetching gem metadata from https://rubygems.org/.Unfortunately, a fatal error has occurred. Please see the Bundler
troubleshooting documentation at http://bit.ly/bundler-issues. Thanks!
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require': no such file to load -- net/https (LoadError)
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from /usr/li...
When overriding #method_missing, remember to override #respond_to_missing? as well
When you use method_missing
to have an object return something on a method call, always make sure you also redefine respond_to_missing?
.
If you don't do it, nothing will break at a first glance, but you will run into trouble eventually.
Consider this class:
class Dog
def method_missing(method_name, *args, &block)
if method_name == :bark
'woof!'
else
super
end
end
end
This will allow you to say:
Dog.new.bark
=> "woof!"
But:
Dog.new.respond_to? :bark
=> false
```...
Run specific version of bundler
You can specify the version of bundler
to execute a command (most often you need an older version of bundler, but don't want to uninstall newer ones):
bundle _1.0.10_ -v
Bundler version 1.0.10
An example is rails 3.2, which freezes bundler
at version ~> 1.0
:
Bundler could not find compatible versions for gem "bundler":
In Gemfile: rails (~> 3.2) was resolved to 3.2.0, which depends on bundler (~> 1.0)
Current Bundler version: bundler (1.13.6)
You can solve this with:
gem install bundler -v 1....
Updated: Test a gem in multiple versions of Rails
Updated the card with our current best practice (shared app code and specs via symlinks).
has_defaults is now a gem
- has_defaults is now a gem, no longer a plugin.
- The plugin version no longer exists. Note that plugins are no longer supported in 3.2.
- If you are working on an application that has the plugin version of
has_defaults
there is no advantage to be gained from upgrading the gem. The gem is there for you should you one day upgrade to Rails 3.2+. - Please don't use the defaults gem which we original forked away from in 2009. It sets defaults when a field is `bl...
Use Memoizer instead of ActiveSupport::Memoizable
ActiveSupport::Memoizable
will be removed from Rails and has a lot of strange caveats that will ruin your day.
Use the Memoizer gem instead. It works in all past and future Railses and has none of the annoying "features" of ActiveSupport::Memoizable
. It just does memoization and does it well.
The syntax is similiar also:
class Foo
include M...
Mysql/Mysql2 agnostic database.yml
If you upgrade to the mysql2 gem, you will run into the problem that the server's database.yml (which is usually not under version control) needs to change exactly on deploy.
You can however make your database.yml work for mysql and mysql2 at the same time. Simpy do this
production:
adapter: <%= defined?(Mysql2) ? 'mysql2' : 'mysql' %>
#...
Security fixes for Rails 2.3
Last week saw a security issue with rails 2.3 that required a fix. While an official patch was provided, the 2.3 branch is no longer maintained. So we forked it.
(I'm sure there are already 100 other forks doing absolutely the same, but they are not very easily discoverable.)
To use our fork, change the gem "rails"...
line in your Gemfile to this:
gem 'rails', :git => 'https://github.com/makandra/rails.git', :branch => '2-3-fixes'
The intent is to make as few changes to the f...
Geordi: Use load-dump script to source a database dump into your database
This script loads a dump into your development database.
You can provide the full path to you database dump like this:
load-dump path/to/my.dump
When you call load-dump
without any arguments it will show a menu with all dumps in your ~/dumps/
folder.
load-dump
This script is part of our geordi gem on github.
Update: Shell script to deploy changes to production and not shoot yourself in the foot
deploy-to-production
now calls Capistrano with bundle exec
since we started to bundle Capistrano in all projects.
Plotting graphs in Ruby with Gruff
Geoffrey Grosenbach has created Gruff for easily plotting graphs. It is written in pure Ruby and integrates with Rails applications.
It provides features as automatic sizing of dots and lines (the more values, the thinner the graph's elements), custom or predefined themes, different styles (bar, line, dot and many more) and multiple graphs in one chart.
Installation
In your Gemfile:
gem 'rmagick', :require => false
gem 'gruff'
Then run bundle install
(and don't forget to restart your development server.)
Usage
This i...
The Ruby Toolbox – a collection of good gems
If you need a gem for a certain purpose, be sure to check this site.
The rankings are determined by counting up the number of forks and watchers of various github projects, so I'd view it less as "this is what I should be using," and more as "these are some things I should check out." At the very least, they're all likely to be under active development and fairly up to date, and it's very useful to see groups of gems broken down by category.