MongoMapper for Rails 2 on Ruby 1.9
MongoMapper is a MongoDB adapter for Ruby. We've forked it so it works for Rails 2.3.x applications running on Ruby 1.9. [1]
makandra/mongomapper
is based on the "official" rails2
branch [2] which contains commits that were added after 0.8.6 was released. Tests are fully passing on our fork for Ruby 1.8.7, REE, and Ruby 1.9.3.
To use it, add this to your Gemfile
:
gem 'mongo_mapper', :git => 'git://github.com/makandra/mongomapper.git', :branch => 'rails2'
...
"Module.const_defined?" behaves differently in Ruby 1.9 and Ruby 1.8
Ruby 1.9 changed the default behavior of Module.const_defined?
from what it was in Ruby 1.8 -- this can be especially painful when external code (read: gems) uses const_defined?
to look something up and gets different results on different Rubies.
Consider this:
module Foo
FOO = 42
end
class Bar
include Foo
end
On Ruby 1.8, Bar
won't have FOO
defined as a constant since that's (even though it's accessible):
1.8.7 > Foo.const_defined? :F...
Fix error "invalid byte sequence in US-ASCII" in .js.erb files
This error can happen in Ruby 1.9.
To fix it, add the following line to the top of your .js.erb
file:
<%# @encoding: UTF-8 %>
How to silence UTF-8 warnings on Rails 2.3 with Ruby 1.9
Rails 2.3.16+ on Ruby 1.9 causes warnings like this:
.../gems/activesupport-2.3.17/lib/active_support/core_ext/string/output_safety.rb:22: warning: regexp match /.../n against to UTF-8 string
Many thanks to grosser for supplying a monkey-patch for Rails 2.3 (Commit f93e3f0ec3 fixed it for Rails 3). Just put it into config/initializers/
to make those warnings go away.
Since we're using RSpec on mos...
A regular expression that will never match
So you have a method returning a regular expression but one case that should not yield a matching Regexp
object but still keep the API stable? Just return one that never matches:
/(?!)/
Fix warning "already initialized constant Mocha" with Rails 3.2
You either have an old version of Mocha and an edge version of Rails 3.2, or you have a new version of Mocha and an old version of Rails. The best solution is to update Mocha to the latest version and switch to Rails edge.
If you are using shoulda-matchers
or another gem that locks Mocha to an old version, you are out of luck.
More info with many other workarounds that you do not want to use can be found here. A hack to work around this case is to add the following file to lib/mocha/setup.rb
:...
rsl/stringex · GitHub
Stringex is a gem that offers some extensions to Ruby's String class. Ruby 1.9 compatible, and knows its way around unicode and fancy characters.
Examples for stringex's String#to_url
method:
# A simple prelude
"simple English".to_url => "simple-english"
"it's nothing at all".to_url => "its-nothing-at-all"
"rock & roll".to_url => "rock-and-roll"
# Let's show off
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
# You do...
lang/unicode_utils · GitHub
UnicodeUtils implements Unicode algorithms for case conversion, normalization, text segmentation and more in pure Ruby code.
If you don't need the ton of features that UnicodeUtils offers, try stringex.
How to fix: RVM does not offer recent Ruby versions
RVM needs to be updated regularly to know of Ruby versions released since installation (or last update).
So if you say rvm install 1.9.3
, but get an old version (basically anything below 1.9.3-p385 when writing this card), your RVM is outdated. \
Fix that by saying:
rvm get stable
After that, rvm install 1.9.3
should install the latest 1.9.3 version.
How to fix: "Error Bundler::HTTPError during request to dependency API"
If bundle install
shows the following message for you ...
Error Bundler::HTTPError during request to dependency API
... upgrade to Bundler ≥ 1.2.4:
gem install bundler
Apparently, it just hides the message.
Edge Rider: Power tools for ActiveRecord scopes
In our continued quest to extract proven code snippets from makandropedia into tested and upgradable gems, we have released Edge Rider.
Edge Rider was created with two intents:
- Provides a number of utility methods to facilitate hardcore work with scopes.
- Provide a stable API for working with scopes across multiple versions of Rails, since Rails has a tradition of breaking details of its scope API every other release.
The gem bundles multiple patches and initializers we've been using for hard...
Traverse an ActiveRecord relation along an association
The Edge Rider gem gives your relations a method #traverse_association
which
returns a new relation by "pivoting" around a named association.
Say we have a Post
model and each Post
belongs to an author:
class Post < ActiveRecord::Base
belongs_to :author
end
To turn a relation of posts into a relation of its authors:
posts = Post.where(:archived => false)
authors = posts.traverse_association(:author)
You can traverse multiple associations in a single call.
E....
The many gotchas of Ruby class variables
TLDR: Ruby class variables (@@foo
) are dangerous in many ways. You should avoid them at all cost. See bottom of this card for alternatives.
Class variables are shared between a class hierarchy
When you declare a class variable, it is shared between this and all descending (inheriting) classes. This is rarely what you want.
Class variables are bound at compile-time
Like unqualified constants, class variables are bound to your current scope *whe...
Prevent double clicks on link_to_remote (simple case)
This works well in the simplified case, when your link disappears after it was clicked.
Let link_to_remote behave as „disabled“ after the first click. Use the :before
hook to replace the orignal link with a link that does nothing but looks like the original link:
:ruby
label = "do_something"
dummy_link = link_to(label)
other_attributes_hash = { :url => ..., :method => ..., ... }
disable_link_option = { :before => "$('your_link_selector').html('#{escape_javascript(dummy_link)}'" } # jquery
= link_to_remote(label, other_att...
Regex: Be careful when trying to match the start and/or end of a text
Ruby has two different ways to match the start and the end of a text:
-
^
(Start of line) and$
(End of line) -
\A
(Start of string) and\z
(End of string)
Most often you want to use \A and \z.
Here is a short example in which we want to validate the content type of a file attachment. Normally we would not expect content_type_1
to be a valid content type with the used regular expression image\/(jpeg|png)
. But as ^
and $
will match lines, it matches both content_type_1
and content_type_2
. Using \A
and \z
will wo...
What The Rails Security Issue Means For Your Startup
January has been a very bad month for Ruby on Rails developers, with two high-severity security bugs permitting remote code execution found in the framework and a separate-but-related compromise on rubygems.org, a community resource which virtually all Ruby on Rails developers sit downstream of. Many startups use Ruby on Rails. Other startups don’t but, like the Rails community, may one day find themselves asking What Do We Do When Apocalyptically Bad Things Happen On Our Framework of Choice? I thought I’d explain that for the general c...
How to update a single gem conservatively
The problem
Calling bundle update GEMNAME
will update a lot more gems than you think. E.g. when you do this:
bundle update cucumber-rails
... you might think this will only update cucumber-rails
. But it actually updates cucumber-rails and all of its dependencies. This will explode in your face when one of these dependencies release a new version with breaking API changes. Which is all the time.
In the example above updating cucumber-rails
will give you Capybara 2.0 (because capybara
is a dependency of `cucumber-rail...
Running "bundle update" without arguments might break your application
Calling bundle update
(without arguments) updates all your gems at once. Given that many gems don't care about stable APIs, this might break your application in a million ways.
To stay sane, update your gems using the applicable way below:
Projects in active development
Update the entire bundle regularily (e.g. once a week). This ensures that your libraries are up-to-date while it's easy to spot major version bumps which may break the app.
Projects that have not been updated in a while
- [Update a single gem conservatively](htt...
RVM: Get rid of your system Ruby
If you worked with a system Ruby before switching to RVM, this system Ruby will be in your way when you switch between projects with/without RVM.
It's hard to get rid of your system Ruby entirely, but you can tell RVM to just use a given Ruby by default, e.g.:
rvm --default use 1.8.7
You need to re-open existing terminals for the changes to take effect.
Note that this will not actually remove the ruby
package from your system, it just isn't used anymore.
Ruby: How to ensure a Tempfile's extension
If you use Tempfile
and pass your own filename containing an extension, it will just be consumed by the Tempfile's filename:
>> Tempfile.new('foobar.xlsx').path
=> "/tmp/foobar.xlsx20130115-19153-4ykpwm-0"
If you want to keep the file extension, pass filename and extension as an array:
>> Tempfile.new([ 'foobar', '.xlsx' ]).path
=> "/tmp/foobar20130115-19153-1xhbncb-0.xlsx"
How to get the hostname of the current machine in Rails or a Ruby script
Use Socket.gethostname
. So for a machine whose hostname is "happycat", it will look like this:
>> Socket.gethostname
=> "happycat"
That should work right away for your Rails application. For plain Ruby, you first need to do:
require 'socket'
If you don't want to use Socket
for some reason, you can still just use the hostname
command, at least on non-Windows machines. Keep in mind that you need to remove trailing white space from the result of the system call.
>> `hostname`
=> "happycat\n"
>> `hostname`.stri...
Fix error: undefined method `desc' for #<Foo::Rake::Taskx1234>
Upgrade the offending gem. If you cannot or don't want to upgrade, lock rake
to 0.8.7
.
will_paginate can paginate plain Ruby arrays
While you are probably using will_paginate to paginate ActiveRecord scopes, it can actually paginate plain Ruby arrays. The resulting arrayish object will have the same methods as a paginated scope, e.g. #total_entries
. This means you can render pagination controls with the same code that works with paginated scopes.
To enable this, add an initializer config/initializers/array_paginate.rb
:
require 'will_paginate/array'
You can now say:
> numbers = (1..1000).to_a
> page = numbers....
Rails 4 Countdown to 2013 | The Remarkable Labs Blog
With the impending release of Ruby on Rails 4, it looks like a lot of developers will be updating their web applications in the coming new year.
To help with this transition, over the next 31 days, we are going to be releasing a series of blog posts going over everything you will need to know about Rails 4 for an effortless upgrade.