Fun with Ruby: Returning in blocks "overwrites" outside return values
In a nutshell: return statements inside blocks cause a method's return value to change. This is by design (and probably not even new to you, see below) -- but can be a problem, for example for the capture method of Rails.
Consider these methods:
def stuff
puts 'yielding...'
yield
puts 'yielded.'
true
end
We can call our stuff method with a block to yield. It works like t...
How to deal with strange errors from WEBrick
If you get errors from your development WEBrick that contain unicode salad, you are probably requesting the page via SSL. \
Since WEBrick does not speak SSL, so change the URL in your browser to use http instead of https.
The error looked like this for me:
[2012-09-06 11:19:07] ERROR bad URI `\000\026\000\020\000'.
[2012-09-06 11:19:07] ERROR bad URI `\000\026\000\020\000'.
[2012-09-06 11:19:07] ERROR bad Request-Line `\026\003\001\000�\001\000\000\177\003\001PHj�\031\006�L��'.
[2012-09-06 11:19:07] ERROR bad URI `\000\026\000\...
Ruby tempfiles
With the the Ruby Tempfile class you can create temporary files. Those files only stick around as long as you have a reference to those. If no more variable points to them, the GC may finalize the object at some point and the file will be removed from the file system. In other words: tempfiles are removed automatically. If you would then try to access the tempfile using its path (which you stored previously), you would get an error because the file no longer exists.
You can proactively unlink your tempfiles to delete them earlier...
SSL certificate problem, when trying to install the libyaml package
I was experiencing the following problem:
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby
So I tried to install the libyaml package via:
rvm pkg install libyaml
This is when I experienced the SSL certification problem mentioned above. This happens when your RVM certificates have expired. You can fix this by updating them via:
rvm get stable
After doing that curl could verify the SSL certificate and I w...
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
...
Remove the module namespace of a qualified Ruby class name
You can use String#demodulize from ActiveSupport:
"ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
"Inflections".demodulize # => "Inflections"
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
specfolder (like [h...
Consul 0.4.0 released
Consul 0.4.0 comes with some new features.
Dependencies
- Consul no longer requires
assignable_values, it's optional for when you want to use theauthorize_values_formacro. - Consul no longer uses
ActiveSupport::Memoizablebecause that's deprecated in newer Railses. Consul now uses Memoizer for this.
Temporarily change the current power
When you set Power.current to a power in an RS...
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_trailto it:
class User < ActiveRecord::Base
has_paper_trail
end
-
- Accessing a previous version
- Saying
user.previous_versiongi...
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
```...
Cucumber: Calling multiple steps from a step definition
When refactoring a sequence of steps to a new, more descriptive step, you can use the steps method and Ruby's %-notation like this:
Given 'I have an article in my cart' do
steps %(
When I go the article list
And I open the first article
And I press "Add to cart"
)
end
This way you can simply copy the steps over without any changes.
Warning: Apparently, steps processes its argument with the Gherkin parse...
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....
Ruby 1.8.7-p370 released
It's the last bugfix release. We will get another year of security fixes, then no more patches.
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_defaultsthere 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...