Ruby 1.9 – Tap my Object

posted by Arkham on October 28th, 2011

Let’ say you need to debug this piece of code:

very_cool_method(egg, sausage)

What would you do? I guess something along the lines of:

spam = very_cool_method(egg, sausage)
p spam

Well, Ruby 1.9 let you do something cooler instead:

very_cool_method(egg, sausage).tap{ |s| p s }

The cool thing about tap is that you can use it to eavesdrop method chains:

very_cool_method(egg, sausage).tap{ |s| p s }.now_make_sandwich_from(bacon)

Hooray! :)

Tags: , , , ,

Rails: how to show SQL logs in console

posted by Arkham on September 2nd, 2011

Simply type in rails console:

ActiveRecord::Base.logger = Logger.new(STDOUT)

Tags: , , ,

Rails 3: how to undo rails generate

posted by Arkham on July 29th, 2011

Have you ever run a

rails generate controller UsersController

and seen your app folder filled with useless files?

create app/controllers/users_controller_controller.rb
invoke erb
create app/views/users_controller
invoke test_unit
create test/functional/users_controller_controller_test.rb
invoke helper
create app/helpers/users_controller_helper.rb
invoke test_unit
create test/unit/helpers/users_controller_helper_test.rb
invoke assets
create app/assets/javascripts/users_controller.js.coffee
invoke scss
create app/assets/stylesheets/users_controller.css.scss

Eww, that’s gross.
To undo that rails generate, simply run:

rails destroy controller UserController

and rails will destroy all those ugly files for you!

remove app/controllers/users_controller_controller.rb
invoke erb
remove app/views/users_controller
invoke test_unit
remove test/functional/users_controller_controller_test.rb
invoke helper
remove app/helpers/users_controller_helper.rb
invoke test_unit
remove test/unit/helpers/users_controller_helper_test.rb
invoke assets
remove app/assets/javascripts/users_controller.js.coffee
invoke scss
remove app/assets/stylesheets/users_controller.css.scss

Tags: , ,

Rails 3: difference between has_many :through and has_and_belongs_to_many

posted by Arkham on May 24th, 2011

From Rails guides:

The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).

Tags: , , ,