Tell RVM which patch level you mean by "1.8.7" or "1.9.3"
When you download or upgrade RVM it has a hardcoded notion which patch level it considers to be "1.9.3".
This can give you errors like "ruby-1.9.3-p392 is not installed" even if you have another Ruby 1.9.3 that will do.
The solution is to define an alias:
rvm alias create 1.9.3 ruby-1.9.3-p385
Fuzzy matching
Another solution is to use rvm with the fuzzy flag, as stated by mpapis.
rvm use --fuzzy .
This will make rvm more intelligent in the Ruby selection. To always do fuzz...
How to discard a surrounding Bundler environment
tl;dr: Ruby's Bundler environment is passed on to system calls, which may not be what you may want as it changes gem and binary lookup. Use Bundler.with_original_env to restore the environment's state before Bundler was launched. Do this whenever you want to execute shell commands inside other bundles.
Example outline
Consider this setup:
my_project/Gemfile # says: gem 'rails', '~> 3.0.0'
my_project/foo/Gemfile # says: gem 'rails', '~> 3.2.0'
And, just to confirm this, these are the installed Rails versions for each ...
How to fix: "unexpected token" error for JSON.parse
When using the json gem, you might run into this error when using JSON.parse:
>> json = 'foo'.to_json
>> JSON.parse(json)
JSON::ParserError: 757: unexpected token at '"foo"'
from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
from (irb):1
Why?
The error above happens because the JSON you supplied is invalid.
While to_json does work correctly, the result itself is not JSON that can be parsed back, as that s...
Ruby: What extend and include do
All Rubyists should be familiar with the common definitions for include and extend. You include a module to add instance methods to a class and extend to add class methods. Unfortunately, this common definition isn’t entirely accurate. It fails to explain why we use instance.extend(Module) to add methods to an instance. Shouldn’t it be instance.include(Module)? To figure this out we’re going to start by discussing where methods are stored.
- include: Adds methods from the provided Module to the object
- extend: Calls include on the single...
YAML syntax compared with Ruby syntax
yaml4r is a juxtaposition of yaml documents and their Ruby couterpart. Thus, it does a great job as YAML-doc, e.g. when writing Rails locale files. Did you know that ...
-
<<is a merge key (similar to&in SASS) - there are variables, called aliases. Definition:
&alias Some content, usage:*alias.
Caveats
Specifying a key twice does not merge the sub keys, but override the first definition, e.g.
de:
car: # overridden
door: Tür
...
def vs. define_method
Ever wondered about the difference between def and define_method? Turns out there are three implicit contexts in Ruby. def and define_method differ in which one they use.
def
- Ruby keyword, starts a method definition
- Opens a new, isolated scope. Variables defined outside are not accessible inside and vice versa.
- Defines an instance method on the receiver (specified before the method name, e.g.
def object.foo); implicit receiver is the default definee
The default definee is not self and...
How to make Rational#to_s return strings without denominator 1 again
The way Rational#to_s works on Ruby has changed from Ruby 1.9 on. Here is how to get the old behavior back.
You may want this for things where Rationals are being used, like when subtracting Date objects from one another.
What's happening?
Converting a Rational to a String usually does something like this:
1.8.7 > Rational(2, 3).to_s
=> "2/3"
1.9.3 > Rational(2, 3).to_s
=> "2/3"
2.0.0 > Rational(2, 3).to_s
=> "2/3"
However, when you have a Rational that simplifies to an integer, you will only get a St...
Protected and Private Methods in Ruby
In Ruby, the meaning of protected and private is different from other languages like Java. (They don't hide methods from inheriting classes.)
private
Private methods can only be called with implicit receiver. As soon as you specify a receiver, let it only be self, your call will be rejected.
class A
def implicit
private_method
end
def explicit
self.private_method
end
private
def private_method
"Private called"
end
end
A.new.implicit
# => "Private called"
A.new.explicit
# => NoMethod...
Ruby: Debugging a method's source location and code
Access the Method object
Dead simple: Get the method object and ask for its owner:
"foo".method(:upcase)
# => #<Method: String#upcase>
"foo".method(:upcase).owner
# => String
Look up a method's source location
Ruby 1.9 adds a method Method#source_location that returns file and line number where that method is defined.
class Example; def method() end; end
# => nil
Example.new.method(:method).source_location
# => ["(irb)", 11]
"foo".method(:upcase).source_location
# => nil # String#upcase is a native method...
Fix „rvm no such file to load -- openssl“ or "rvm no such file to load -- zlib"
For example if you use rvm and get this message:
ERROR: Loading command: install (LoadError)
no such file to load -- zlib
ERROR: While executing gem ... (NameError)
uninitialized constant Gem::Commands::InstallCommand
You've installed your ruby without having all required libraries.
I don't know why there isn't a Warning message if you install a ruby with rvm and didn't have libraries like openssl and zlib.
To fix this you can execute this:
#to show the requirements for your system
rvm requireme...
Ruby 1.9 or Ruby 2.0 do not allow using shortcut blocks for private methods
Consider this class:
class Foo
private
def test
puts "Hello"
end
end
While you can say create a block to call that method (using ampersand and colon) on Ruby 1.8, ...
1.8.7 > Foo.new.tap(&:test)
Hello
=> #<Foo:0x1e253c8>
... you cannot do that on Ruby 1.9 or 2.0:
1.9.3 > Foo.new.tap(&:test)
NoMethodError: private method `test' called for #<Foo:0x00000001e8c258>
^
2.0.0 > Foo.new.tap(&:test)
NoMethodError: private method `test' called for #<Foo:0x000000027bc738...
Different behavior for BigDecimal#floor in Ruby 1.8 and Ruby 1.9
Ruby 1.8 (supplied by Rails' ActiveSupport)
>> BigDecimal.new("0.1").floor.class
=> BigDecimal
Ruby 1.9 (supplied by Ruby 1.9 itself)
>> BigDecimal.new("0.1").floor.class
=> Fixnum
In fact, Float#floor has changed from Ruby1.8 to Ruby 1.9 which is used by BigDecimal#floor internally.
Attached initializer backports Ruby 1.9 behavior to Ruby 1.8.
How to: Ruby heredoc without interpolation
When you use heredoc, string interpolation is enabled by default:
x = "Universe"
<<-MESSAGE
Hello #{x}
MESSAGE
# => "Hello Universe"
This may be impractical sometimes. To avoid interpolation in heredoc strings, simply enclose your heredoc marker with single quotes:
x = "Universe"
<<-'MESSAGE'
Hello #{x}
MESSAGE
# => "Hello #{x}"
That will make the string behave like a single-quoted string, so sequences like \n wil...
Capistrano: Bundler stalls and asks for "Username"
Given you use Capistrano together with bundler to automatically install your gems when deploying.
I recently had the problem that Capistrano stalled like this:
[err :: host.name.tld] Username:
It turned out that I this originated from GitHub. We had a gem in our Gemfile that explicitly pointed to a GitHub URL like that:
gem 'foogem', :git => 'https://github.com/blubb/foogem.git'
The URL was returning a 404 which caused the problems. You have to get another gem or point to a fork on GitHub.
instance_eval behaves different in Ruby 1.8 and Ruby 1.9, use instance_exec instead
In Ruby 1.9, instance_eval calls the block the with receiver as the first argument:
- In Ruby 1.8,
receiver.instance_eval(&block)callsblock.call() - In Ruby 1.9,
receiver.instance_eval(&block)callsblock.call(receiver)
This will blow up in your face in Ruby 1.9, where a lambda crashes when it is called with a different number of arguments:
wrong number of arguments (1 for 0) (ArgumentError)
Forget that instance_eval ever existed. Use instance_exec instead, which behaves consistently across all Rubies.
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.