No more file type confusion in TextMate2
When using TextMate2 with the cucumber bundle, it does not recognize step definitions (e.g. custom_steps.rb
) as such but believes they are plain Ruby files. But there is help!
Solution
Add these lines to the bottom of your .tm_properties
file (in ~/
for global settings, in any directory for per-project settings):
[ "*_steps.rb" ]
fileType = "source.ruby.rspec.cucumber.steps"
Apparently, this works for any files. Define a regex and specify custom settings. The attached article lists all available configuration options (whic...
Why Ruby Class Methods Resist Refactoring
In a nutshell:
- Splitting a long method into sub methods is easier in instances since it is in classes. Since you must not save state in a class, you need to pass around context as a long chain of parameters again and again.
- If your public API has a single entry point, you can still have a class-level method that takes care of constructing the instance etc. So it's all win.
Thread Safety With Ruby — Luca Guidi
Ruby’s model for concurrency is based on threads. It was typical approach for object oriented languages, designed in the 90s. A thread is sequence of instructions that can be scheduled and executed in the context of a process. Several threads can be running at the same time.
Ruby’s VM process allocates a memory heap, which is shared and writable by threads. If incorrectly coordinated, those threads can lead to unexpected behaviors.
Ruby on Rails 4 and Batman.js
Batman is an alternative Javascript MVC with a similar flavor as AngularJS, but a lot less features and geared towards Ruby on Rails.
The attached link leads to a tutorial for a small blog written with Rails / Batman.js.
I'm collecting other Batman.js resources in my bookmarks.
How Ruby method lookup works
When you call a method on an object, Ruby looks for the implementation of that method. It looks in the following places and uses the first implementation it finds:
- Methods from the object's singleton class (an unnamed class that only exists for that object)
- Methods from prepended modules (Ruby 2.0+ feature)
- Methods from the object's class
- Methods from included modules
- Methods from the class hierarchy (superclass and its an...
Collection of Rails development boosting frameworks
Development environment setup
- Rails Composer
-
Basically a comprehensive Rails Template. Prepares your development environment and lets you select web server, template engine, unit and integration testing frameworks and more.
Generate an app in minutes using an application template. With all the options you want!
Code generators
- Rails Bricks
-
A command line wizard. Once you get it running, it creates sleek applications.
RailsBricks enables you to cre...
Bash: Heavy headings for CLI
To print a colored full-width bar on the bash, use this bash script expression:
echo -e '\033[37;44m\nHEADING\033[0m\nLorem ipsum ...'
In Ruby:
puts "\033[37;44m\n #{text}\033[0m" # blue bar
Notes: -e
turns on escape character interpretation for echo
. See this card for details on bash formatting.
The line above will print:
Some nifty Rails Rake tasks
Did you know?
rake stats # => LOC per controllers, models, helpers; code ratios, and more
rake notes # => collects TODO, FIXME and other Tags from comments and displays them
rake about # (Rails 3+) => Rails, Ruby, Rake, Rack etc. versions, used middlewares, root dir, etc.
String#indent: Know your definitions!
String#indent
is not a standard Ruby method. When you use it, be sure to know where this method comes from. Many Gems shamelessly define this method for internal usage, and you'll never know when it may be removed (since it's usually not part of the Gem's API).
Unless you're using Rails 4 (which brings String#indent
in ActiveSupport), you'll be best of defining it yourself. This card has it for you.
Gems that define String#indent
(incomplete)
----------------------------...
Finding a method name on a Ruby object
Wondering how a specific method on an object is exactly named? You can use Enumerable#grep
to detect it in the array of methods.
@user.methods.grep /name/ # => [:name, :first_name, :last_name]
You can also call #private_methods
or #public_methods
. To find only relevant methods, it is suggested to subtract generic methods like this:
User.methods - Object.methods
User.methods - ActiveRecord::Base.methods
@user.methods - Object.instance_methods
@user.methods - ActiveRecord::Base.instance_methods
How to call overwritten methods of parent classes in Backbone.js
When you are working with Backbone models and inheritance, at some point you want to overwrite inherited methods but call the parent's implementation, too.
In JavaScript, there is no simple "super
" method like in Ruby -- so here is how to do it with Backbone.
Example
BaseClass = Backbone.Model.extend({
initialize: function(options) {
console.log(options.baseInfo);
}
});
MyClass = BaseClass.extend({
initialize: function(options) {
console.log(options.myInfo);
}
});
ne...
Ruby number formatting: only show decimals if there are any
Warning: Because of (unclear) rounding issues and missing decimal places (see examples below),
do NOT use this when dealing with money. Use our amount helper instead.
In Ruby, you can easily format strings using %
(short for Kernel#sprintf):
'%.2f' % 1.23456 #=> 1.23
'%.2f' % 2 #=> 2.00
However, what if you only want the decimals to be shown if they matter? There is g
! It will limit the total number of displayed digits, disregarding...
rbenv: How to switch to another Ruby version
If you want to switch to another ruby versions, you have several options, depending on what you want: Do you want to switch temporarily, per project, or globally?
Here is a short guide.
Unlike RVM, rbenv does not offer a command like rvm use
. By default, it respects your project's .ruby-version
file.
If you need to change manually, you have several options:
rbenv shell
rbenv local
rbenv global
You probably want rbenv shell
.
How to switch your Ruby version temporarily: rbenv shell
In case you only want to...
krisleech/wisper
Publish/subscribe for Ruby classes. Bonus: You do not have to declare events before using them.
How to load only a subset of a massive MySQL dump
I had a huge MySQL dump that took forever (as in: days) to import, while I actually just wanted to have the full database structure with some data to use on my development machine.
After trying several suggestions on how to speed up slow MySQL dump imports (which did not result in any significant improvement), I chose to import just some rows per table to suffice my needs. Since editing the file was not an option, I used a short Ruby script to manage that.
Here is how:
pv huge.dump | ruby -e 'ARGF.each_line { |l| m = l.match(/^INSERT ...
Installing therubyracer and libv8 with Ruby 1.8 on OSX Mavericks
There seems to be no way to use therubyracer -v '0.11.4'
and libv8 -v '3.11.8.17'
on OS X Mavericks.
However, running bundle update therubyracer
worked for me. It installed therubyracer -v '0.12.1'
and libv8 -v '3.16.14.3'
and I had not side effects.
Log of my attempts to get it working
Probably you got here when bundling failed building native extensions for therubyracer
.
The libv8
(3.3.10.4) should have been installed when bundling. Unfortunately it is not building correctly on Mavericks, so the libv8.a
f...
How to install older versions of REE with rbenv on Ubuntu 12.04
Rbenv won't compile REE 2011.03 properly on Ubuntu 12.04, failing with an error in tcmalloc.cc
.
If you want to keep tcmalloc functionality, you can do it like this:
- Open
~/.rbenv/plugins/ruby-build/share/ruby-build/ree-1.8.7-2011.03
- Replace the file's contents with those from fgrehm's gist
-
rbenv install
again
You could also try CONFIGURE_OPTS="--no-tcmalloc" rbenv install
, but that would disable tcmalloc. Doing that, you might still encounter issues with ossl_ssl.c
-- which is ...
The new Modularity 2 syntax
We have released Modularity 2. It has many incompatible changes. See below for a script to migrate your applications automatically.
There is no does method anymore
We now use traits with the vanilla include
method:
class Article < ActiveRecord::Base
include DoesTrashable
end
When your trait has parameters, use square brackets:
class Article < ActiveRecord::Base
include DoesStripFields[:name, :brand]
end
Note how you ...
Careful with '||=' - it's not 'memoize'
When you do something like this in your code:
def var_value
@var ||= some_expensive_calculation
end
Be aware that it will run some_expensive_calculation every time you call var_value if some_expensive_calculation returns nil.
This illustrates the problem:
def some_expensive_calculation
puts "i am off shopping bits!"
@some_expensive_calculations_result
end
When you set @some_expensive_calculations_result to nil, ||= runs some_expensive_calculation every time....
Opal, A new hope (for Ruby programmers)
Opal is a source to source ruby to javascript compiler, corelib and a runtime implementation that currently passes 3000 rubyspecs w/a reachable goal of passing them all.
Sort a Ruby array with multiple criteria
If you want to sort a Ruby array with a primary, secondary, etc. criterium, use a sort_by
that contains a block:
users.sort_by { |user| [user.age, user.name] }
This trick also works with our natural sort method.
How to fix "undefined method `name' for Array" error when running bundled commands on Ruby 1.8.7 + Rails 2.3
On recent/fresh installations of Ruby 1.8.7 you may encounter this error why calling any bundled binary (or just bundle exec
):
/home/arne/.rvm/gems/ruby-1.8.7-p374@global/gems/rubygems-bundler-1.4.2/lib/rubygems-bundler/noexec.rb:75:in `setup': undefined method `name' for #<Array:0x7fe04783ef30> (NoMethodError)
from /home/arne/.rvm/rubies/ruby-1.8.7-p374/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:29:in `map'
...
Apparently, this is due to bundler (or maybe the rubygems-bundler
that RVM supplies by default) no lon...