When using time zones, beginning_of_day / end_of_day is broken in Rails 2 for any Date or DateTime

Using beginning_of_day or end_of_day on Date or DateTime objects in Rails 2.x applications will never respect time zones, which is horrible.\
This is fixed in Rails 3, though.

Even when using Date.current or DateTime.current you will get regular Time or DateTime objects:

>> Date.current.beginning_of_day.class
=> Time # not a ActiveSupport::TimeWithZone as expected
>> DateTime.current.beginning_of_day.class
=> DateTime ...

Nested controller routes (Rails 2 and 3)

In order to keep the controllers directory tidy, we recently started to namespace controllers. With the :controller option you can tell Rails which controller to use for a path or resource. For nested resources, Rails will determine the view path from this option, too.

That means the following code in routes.rb

resources :users do
  resource :profile, controller: 'users/profiles' #[1]
end

… makes Rails expect the following directory structure:

app/
  controllers/
    users/
      profiles_controller.rb
    users_control...

Enable NewRelic monitoring [for Rails] on specific hosts only

If you need to enable NewRelic monitoring on certain machines within the same Rails environment, a simple solution is to utilize the respective hostnames of you machines.

For example, if you have 8 application servers (e.g. app1.example.com, app2.example.com, ...) and want to enable NewRelic on app1 and app2 only, utilize those steps to do so:

  1. Put the attached file into your config directory (config/custom_new_relic_configuration.rb).
  2. Specify on which hosts NewRelic should be enabled (see NEWRELIC_HOSTS constant and list ...

markbates/coffeebeans

When CoffeeScript was added to Rails 3.1 they forgot one very important part, the ability to use it when responding to JavaScript (JS) requests!

In Rails 3.1 it’s incredibly easy to build your application’s JavaScript using CoffeeScript, however if you fire off an AJAX request to your application you can only write your response using regular JavaScript and not CoffeeScript, at least until CoffeeBeans came along.

Ruby, Rails, Web2.0 » Blog Archive » Great Ruby on Rails REST resources

I have been playing around with RESTful Rails recently. Below is my collection or Rails REST howtos, tutorials and other resources I have found so far.

iPhone on Rails and ObjectiveResource; Making communication between the iPhone and a Rails web-service pain-free.

ObjectiveResource is an Objective-C port of Ruby on Rails' ActiveResource. It provides a way to serialize objects to and from Rails' standard RESTful web-services (via XML or JSON) and handles much of the complexity involved with invoking web-services of any language from the iPhone.

Ruby on Rails » Keeping Up With The Joneses: Keeping Rails and its extensions up to date » Pathfinder Development

There are many wonderful things about Rails and the Rails ecosystem. A clean, well-lighted path for keeping all your extensions up to date is not one of them.

Rails: Default generators

This is a visualization of the files that will be generated by some useful rails generators. Invoke a generator from command line via rails generate GENERATOR [args] [options]. List all generators (including rails generators) with rails g -h.

generator model migration controller entry in routes.rb views tests
scaffold
resource ✔ ...

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...

Rails 3 routing: Be careful with matching routes *including their format*

Today, this line made me trouble. Can you spot the mistake?

match 'sitemap.xml' => 'feeds#sitemap', :constraints => { :format => 'xml' }, :as => 'sitemap'

The mistake is to match sitemap.xml. Rails will by default strip any dot-anything, remember it as desired format and forward the rest of the request to the routing engine. Since we're making .xml part of the match, it is not available for format determination and Rails will set the format to html.

Unfortunately, the constraint won't complain in this case and Rails even ren...

Installing Rails on a fresh system

  1. Install Ruby from the Ubuntu repository: sudo apt-get install ruby ruby-dev \
    ruby is the meta package. If you want to explicitly install 1.8 or 1.9, install ruby1.8 or ruby1.9 instead (the same applies for ruby-dev).
  2. Do not install RubyGems from the repository but install the version from the webpage instead.
  3. Get Bundler: sudo gem install bundler

Rails and other gems for a project should now be installed via bundle install from the...

3 ways to run Spring (the Rails app preloader) and how to disable it

spring ...

The most obvious way to use spring is to call it explicitly:

spring rails console
spring rake db:migrate

Binstubs

Binstubs are wrapper scripts around executables. In Rails they live inside bin/. If you run spring binstub --all, your binstubs will be using Spring.

bin/rails console
bin/rake db:migrate

bundle exec rails ...

Bundle exec is inconsistent when it comes to spring. Some commands will use it, some won't.

bundle exec rails console # starts Spring...

Rails: Invoking a view helper from the console

There are a few ways to access view helpers from the Rails console. The easiest way is the helper shortcut:

helper.translate 'i18n.string'
helper.your_helper_method

If the desired helper renders a view template, you need this setup:

view_paths = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
av_helper = ActionView::Base.new(view_paths).extend YourHelperModule

av_helper.your_helper_method

ExceptionNotification gem will only show application backtrace starting on Rails 4

Starting with Rails 4.0, when you get an exception reported via the ExceptionNotification gem, you will only see a very short backtrace with all backtrace lines from gems or ruby libraries missing.

This happens, because the ExceptionNotification gem uses Rails' default backtrace cleaner. To get a full backtrace in exception emails, you can remove the comment from this line in config/initializers/backtrace_silencers.rb:

Rails.backtrace_cleaner.remove_silencers!

Note that this will break the "Application Trace" functionality o...

Rails 3.1 gives you free down migrations

In Rails 3.1+, instead of defining a separate up and down method you can define a single method change:

class AddComparisonFieldsToReport < ActiveRecord::Migration
  def change
    add_column :reports, :compare, :boolean
    update "UPDATE reports SET compare = #{quoted_false}"
    add_column :reports, :compare_start_date, :date
    add_column :reports, :compare_end_date, :date
  end
end

Migrating up works as expected:

b rake db:migrate
==  AddComparisonFieldsToReport: migrating ====================================
-- ad...

Rails + Sidekiq::Web: Configuration for wildcard session cookies

When you're using Sidekiq::Web to monitor the Sidekiq status AND have your session cookie configured to a wildcard domain like .example.com, you need to take an additional step to keep your cookies valid.

Issue

Sidekiq::Web is mounted into your Rails application and will use the Rails session cookie for protection from CSRF attacs. While it somehow figures out the cookie name, it does NOT respect cookie configuration like a custo...

See which Rails applications are being served by your Passenger

To obtain a list of Passenger processes with their application directories and memory usages, you can say

sudo passenger-memory-stats

This will output a list like this:

----- Passenger processes -----
PID    VMSize    Private  Name
-------------------------------
671    112.9 MB  95.5 MB  Rails: /opt/www/project1/current
707    79.4 MB   60.5 MB  Rails: /opt/www/project2/current
1094   88.1 MB   69.3 MB  Rails: /opt/www/project3/current
1260   81.6 MB   62.6 MB  Rails: /opt/www/project4/current
1269   7...

Zeus promises to make rails development faster

I am talking about development speed. When your application starts growing and you start adding gems, it starts to take really long to start up, be it the server, console or just running a single spec.

Zeus is smart, you don’t have to put it in your Gemfile or run it with Bundler, all you need to do is create a JSON config file via zeus init and then start the server zeus start.

After that, you’re ready to go, all you need to do is prefix every command with zeus. That means rails server becomes zeus server, `rails console...

How to get the hostname of the current machine in Rails or a Ruby script

Use Socket.gethostname. So for a machine whose hostname is "happycat", it will look like this:

>> Socket.gethostname
=> "happycat"

That should work right away for your Rails application. For plain Ruby, you first need to do:

require 'socket'

If you don't want to use Socket for some reason, you can still just use the hostname command, at least on non-Windows machines. Keep in mind that you need to remove trailing white space from the result of the system call.

>> `hostname`
=> "happycat\n"
>> `hostname`.stri...

Ruby and Rails deprecation warnings and how to fix them

Add deprecation warnings and their solution or link to available solutions.

Global access to Rake DSL methods is deprecated. Please include Rake::DSL into classes and modules which use the Rake DSL methods.

Open your Rakefile and add the following line above YourApp::Application.load_tasks:

YourApp::Application.class_eval do
  include Rake::DSL
end

Use of ole/file_system is deprecated. Use ole/storage (the file_system api is recommended and enabled by default)...

Upgrading a Rails 3.2 application to Ruby 2.1 is really easy

Upgrading from Ruby 1.8.7 to 2.1.2 took me an hour for a medium-sized application. It involved hardly any changes except

  • removing the occasional monkey patch where I had backported functionality from modern Rubies
  • Migrating from require to require_relative where I loaded RSpec factories in Cucumber's env.rb (the Rails application root is no longer in the load path by default)
  • replacing the old debugger with byebug
  • removing sytem_timer from Gemfile (see [this SO thread](http://stackoverflow.com/questions/7850216/how-to-inst...

Use Sass without Rails

You don't need a Rails application to use Sass. Even when you're working on a static site you can generate your CSS through Sass.

  • Install Sass with sudo gem install haml
  • Create a folder sass in the folder, that stores your stylesheets, e.g. mkdir css/sass
  • In a separate terminal window, run sass --watch css/sass:css. This will watch your sass files for changes and rewrite stylesheets as required.

This even works on Windows.

Note about your .gitignore

You might want to change our [typical .gitignor...

How to upgrade Cucumber on Rails 3+

  1. Run bundle update cucumber capybara cucumber-rails to update to the newest versions.

  2. Backup your features/support/path.rb to be able to add your own paths again after the cucumber installation script in step 4.

  3. Backup your features/support/env.rb file to be able to reintegrate parts like your blueprints setup:

    ENV["RAILS_ENV"] ||= "cucumber"
    require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
    require 'spec/support/blueprints'
    
  4. Run `$ rails generate cucumber:install --capyba...

Rendering 404s for missing images via Rails routes

When you load a dump for development, records may reference images that are not available on your machine.

Requests to those images may end up on your application, e.g. if a catch-all route is defined that leads to a controller doing some heavy lifting. On pages with lots of missing images, this slows down development response times.

You can fix that by defining a Rails route like this:

if Rails.env.development?
  scope format: true, constraints: { format: /jpg|png|gif/ } do
    get '/*anything', to: proc { [404, {}, ['']] }

...