Disabling Spring when debugging
Spring is a Rails application preloader. When debugging e.g. the rails gem, you'll be wondering why your raise, puts or debugger debugging statements have no effect. That's because Spring preloads and caches your application once and all consecutive calls to it will not see any changes in your debugged gem.
Howto
Disable spring with export DISABLE_SPRING=1 in your terminal. That will keep Spring at bay in that terminal session.
In Ruby, [you can only write environment variables that subproc...
How to create Rails Generators (Rails 3 and above)
General
- Programatically invoke Rails generators
-
Require the generator, instantiate it and invoke it (because generators are
Thor::Groups, you need to invoke them withinvoke_all). Example:require 'generators/wheelie/haml/haml_generator' Generators::HamlGenerator.new('argument').invoke_allOther ways: Rails invokes its generators with
Rails::Generators.invoke ARGV.shift, ARGV. From inside a Rails generator, you may call the [inherited Thor methodinvoke(args=[], options={}, config={})](https://github...
docopt: A promising command line parser for (m)any language
docopt helps you define interface for your command-line app, and automatically generate parser for it.
docopt is based on conventions that are used for decades in help messages and man pages for program interface description. Interface description in docopt is such a help message, but formalized. Here is an example:
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h |...
Remove Rubygems deprecation warnings
Rubygems can produce lots of deprecation warnings, but sometimes, you cannot fix them. To have a tidy terminal with output that matters, add this to the top of your Gemfile and enjoy silence:
Deprecate.skip = true if defined?(Deprecate.skip)
Gem::Deprecate.skip = true if defined?(Gem::Deprecate.skip)
# all gems go here ...
Hash any Ruby object into an RGB color
If you want to label things with a color but don't actually care which cholor, you can use the attached Colorizer class.
To get a completely random color (some of which will clash with your design):
Colorizer.colorize(some_object) # => "#bb4faa"
To get similiar colors (e. g. bright, pale colors of different hues):
# random hue, saturation of 0.5, lightness of 0.6
Colorizer.colorize_similarly(some_object, 0.5, 0.6) # => "#bbaaaa"
Also see the color gem.
Debugging AJAX requests with better_errors
better_errors is an awesome gem for enhanced error pages in development, featuring a live-REPL for some light debugging.
To debug the exception you got on an AJAX-Request, visit /__better_errors on your app's root path (e.g. http://localhost:3000/__better_errors). It shows the error page for the last exception that occurred, even when it has been triggered by an AJAX request.
Ruby: How to camelize a string with a lower-case first letter
If you want to do JavaScript-style camelization, ActiveSupport's String#camelize method can actually help you out. Simply pass a :lower argument to it.
>> 'foo_bar_baz'.camelize
=> "FooBarBaz"
>> 'foo_bar_baz'.camelize(:lower)
=> "fooBarBaz"
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 shellrbenv localrbenv 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...