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
spec
folder (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_for
macro. - Consul no longer uses
ActiveSupport::Memoizable
because 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_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
```...
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_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...
Rack dies when parsing large forms
- Rack has a limit for how many form parameters it will parse.
- This limit is 65536 by default.
- There is a bug in Rack that will incorrectly count the number of input fields in nested forms. In my case a form with 1326 input fields was enough to break the default limit.
- If Rack thinks your request is too large, the request will fail with a low-level Ruby message like Fix: "undefined method `bytesize' for #" or the standard Rails error box.
- You ...
Updated: Ruby doesn't sort strings with German umlauts correctly
I posted a solution which is awesome and also does natural sorting.
Ruby: Replacing Unicode characters with a 7-bit transliteration
Sometimes you need to remove high Unicode characters from a string, so all characters have a code point between 0 and 127. The remaining 7-bit-encoded characters ("Low-ASCII") can be transported in most strings where escaping is impossible or would be visually jarrring.
Note that transliteration this will change the string. If you need to preserve the exact string content, you need to use escaping.
Using ActiveSupport
ActiveSupport comes with a `#tran...
Don't use Ruby 1.9.2
Ruby 1.9.2 is very slow when loading files, especially starting Rails servers or running specs takes forever.
Do yourself a favor and upgrade to 1.9.3.
Properly require your "spec_helper"
Always use simply
require 'spec_helper'
If you mix it up like
require 'spec_helper'
require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/../../spec_helper'
require File.expand_path('spec/spec_helper')
the file will be executed each time, since Ruby (at least 1.8) identifies it simply by the string you passed to "require".
Calendar quarter calculations in Ruby and MySQL
ActiveSupport >= 3 has
Date.parse('2011-02-10').beginning_of_quarter #=> 2011-01-01
Date.parse('2011-02-10').end_of_quarter #=> 2011-03-31
You can manually calculate the quarter index like
(Date.parse('2011-02-10').month / 3.0).ceil #=> 1
Yes, you do actually divide by 3.0
, not 4.0
.
MySQL has
SELECT QUARTER('2011-02-10'); #=> 1
Organize large I18n dictionary files in Ruby on Rails
If you're suffering from a huge de.yml
or similiar file, cry no more. Rails lets you freely organize your dictionary files in config/locales
.
My organization works like this:
-
config/locales/rails.de.yml
modified Rails boilerplate -
config/locales/faker.de.yml
modified Faker boilerplate -
config/locales/models.de.yml
model names, attribute names, assignable_value labels - `config/locales/views.de.y...
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...