Parallel gem installing using Bundler
Bundler 1.4.0 (still beta) can install gems in parallel, making a run of bundle install much faster.
The "private" modifier does not apply to class methods or define_method
Ruby's private keyword might do a lot less than you think.
"private" does not apply to class methods defined on self
This does not make anything private:
class Foo
private
def self.foo
'foo'
end
end
You need to use private_class_method instead:
class Foo
def self.foo
'foo'
end
private_class_method :foo
end
"private" does not apply to define_method
This does not make anythin...
RubyLTS
RubyLTS is a long term supported fork of Ruby 1.8 that will continue to receive security updates for the forseeable future.
exception_notification 4.0.0+ makes it easier to ignore errors, crawlers
The new exception_notification has awesome options like :ignore_crawlers => true and :ignore_if => lambda { ... }. These options should be helpful in ensuring every notifications means something actionable (instead of a long log of failures that just scrolls by).
Note that you should not ignore crawlers by default. Ideally, cool URLs never change and always respond with a helpful redirect or similar.
Ignore Errors like this:
# config/initializers/exception_notification.rb
Ex...
Consul 0.9 lets you optimize records checks
Consul 0.9 comes with many new features to optimize powers that only check access to a given record. e.g. Power.current.post?(Post.last). See below for details.
Powers that only check a given object
Sometimes it is not convenient to define powers as a collection. Sometimes you only want to store a method that
checks whether a given object is accessible.
To do so, simply define a power that ends in a question mark:
class Power
...
power :upd...
Cryptic Ruby Global Variables and Their Meanings
The linked page lists and explains global Ruby "dollar" variables, such as:
-
$:(load path) -
$*(ARGV) -
$?(Last exit status) -
$$(PID) -
$~(MatchDatafrom last successful match) - ...and many more you'll need when reading weird code.
Regex
-
$~(lastMatchData) -
$1 $2 $3 $4(match groups from the last pattern match) -
$&(last matched string) -
$+(last match group) - `$`` (the string before the last match)
-
$'(the string after the last match
See [this extensive list of variables](http://www.tu...
Short lambda syntax in Ruby 1.9
Ruby 1.9 brings a shorter way to define lambdas using the -> operator:
twice = -> (x) { 2 * x }
twice.call(5) # => 10
This is equivalent to:
twice = lambda {|x| 2 * x }
twice.call(5) # => 10
Note that the syntax is subtly different from Coffeescript where you define function parameters before the arrow: (x) -> { 2 * x }.
Sprites with Compass
Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.
There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...
Live CSS / view reloading
Next time you have to do more than trivial CSS changes on a project, you probably want to have live CSS reloading, so every time you safe your css, the browser updates automatically. It's pretty easy to set up and will safe you a lot of time in the long run. It will also instantly reload changes to your html views.
Simply follow the instructions below, taken from blog.55minutes.com.
Install CSS live reload (only once per project)
- Add th...
Batch-process text files with ruby
Did you know you can do in-place batch processing with plain ruby?
The following script will in-place replace "foo" with "bar" in all files you feed it. Call it with ./my_script path/to/my/files/*
#!ruby -i -p
$_.gsub!(/foo/, "bar")
"'-i -p" means:
Ruby will run your script once for each line in each file. The line will be placed in $_. The value of $_ at the end of your script will be written back to the file.
Shorter
Using the Kernel#gsub shorthand for $_.gsub!:
#!ruby -i -p
gsub(/foo/, "bar")
S...
Upgrading Rails 2 from 2.3.8 through 2.3.18 to Rails LTS
This card shows how to upgrade a Rails 2 application from Rails 2.3.8 through every single patch level up to 2.3.18, and then, hopefully, Rails LTS.
2.3.8 to 2.3.9
This release has many minor changes and fixes to prepare your application for Rails 3.
Step-by-step upgrade instructions:
- Upgrade
railsgem - Change your
environment.rbso it saysRAILS_GEM_VERSION = '2.3.9' - Change your ...
Rails: Have different session secrets for all environments
The Rails secret_token must be unique for each application and any instance of it. If not, someone could exploit this by creating a user with ID = 1 (e.g. on staging), sign in and then use that cookie to authenticate on another site (e.g. on production, where the user with ID = 1 probably is the admin).
Here is a one-for-all solution that does not affect current production users, leaving the production token unchanged: prefix the existing secret_token with #{Rails.env unless Rails.env.production?}.
Note: There may be tokens in ...
Before you make a merge request: Checklist for common mistakes
Merge requests are often rejected for similar reasons.
To avoid this, before you send a merge request, please confirm that your code ...
- has been reviewed by yourself beforehand
- fulfills every requirement defined as an acceptance criterion
- does not have any log or debugging statements like
console.log(...),byebugetc. - has green tests
- has tests...
Virtus: Coercing boolean attributes
TLDR
Do it like this:
attribute :active, Virtus::Attribute::Boolean
Long story
In Virtus you define attribute with their type like this:
attribute :name, String
attribute :birthday, Date
When defining a boolean attributes, you will probably write it like this:
attribute :active, Boolean
The problem is, there is not actually a Boolean class in Ruby (there's only TrueClass and FalseClass), so use Virtus::Attribute::Boolean instead.
The reason whil...
marcandre/backports · GitHub
Essential backports that enable many of the nice features of Ruby 1.8.7 up to 2.0.0 for earlier versions.
Subscribe to Rails security mailing list without Google account
The Ruby on Rails security list archive can be found here: http://groups.google.com/group/rubyonrails-security
You can subscribe to this mailing list without a Google account by pasting this URL into your browser (after replacing the email address obviously).
http://groups.google.com/group/rubyonrails-security/boxsubscribe?email=your.name@example.com
^^^^^^^^^^^^^^^^^^^^^ <- Change this
Ruby Scripts: Select the Ruby version in the shebang
As Bill Dueber has on his blog, you can call rvm in the shebang to select a Ruby version like this:
#!/usr/bin/env rvm 1.9 do ruby
Standard arguments to do apply, see $> rvm help do.
Using Thin for development (with SSL)
Note: These instructions are for a quick per-project setup and may require you to change code. If you generally need SSL for development, you probably want to use Passenger.
- Create a directory
.sslin your home directory. Go there and create a self-signed certificate. It is important to enterlocalhost.sslasCommon Namewhen asked. This is to mak...
Detect city, country from IP address
- You can detect city and country from an IP address by using the GeoLite database. This is a flat file you can copy into your project (~ 20 MB).
- You can access the database using the geoip gem.
- You need to attribute MaxMind if you are using the data.
- Accuracy sort of sucks. For most countries 1/3 of addresses cannot be resolved within 40 kilometers, probably because the Inter...
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
...