Rails routes: Extracting collection actions into their own controllers

Let's say you have two screens:

  1. Show a given project
  2. Show a report for all projects

Ideally you want both screens to be handled by different controllers like this:

GET /projects/:id        => ProjectsController#show
GET /projects/report     => Projects::ReportsController#show

What seems like a simple requirement is a little awkward to configure in your routes.
Obviously the report should be a singleton resource, but how can we nest it into the Projects:: namespace?

What does not work is this:

resources :proj...

What we know about PDFKit

What PDFKit is

  • PDFKit converts a web page to a PDF document. It uses a Webkit engine under the hood.
  • For you as a web developer this means you can keep using the technology you are familar with and don't need to learn LaTeX. All you need is a pretty print-stylesheet.

How to use it from your Rails application

  • You can have PDFKit render a website by simply calling PDFKit.new('http://google.com').to_file('google.pdf'). You can then send the...

Testing drag&drop with Selenium

When using jQueryUI's Sortable plugin (either directly or via Angular's ui.sortable), you might struggle testing your nice drag&drop GUI since Selenium webdriver does not support native dragging events.

But jQueryUI uses jquery.simulate for their testing, so why shouldn't you? There is even an extension to it that makes testing drag & drop quite easy.

Here is what you need:

  1. jquery.simulate.js
  2. [`jquery.simula...

Rest-ORM for Angular: Restmod

Restmod creates objects that you can use from within Angular to interact with your RESTful API.

Feedjira

Great gem to consume RSS feeds. I was missing some features on Ruby's RSS::Parser that I found in Feedjira:

  • Speed
  • Does not break on slightly malformed RSS feeds (like a missing length attribute on an <enclosure> tag on gizmodo.de's feed)
  • It automatically resolves Feedburner-mangled URLs (hooray!)

The GitHub project has only a minimalistic readme. You can find its documentation on their homepage.

gazay/ids_please

Parses URLs of social networks to extract IDs or screen names.

It does not get confused by child routes: you may also pass URLs like a user's twitter photo stream and the gem will extract their twitter ID .

Note that it just parses URLs, and does nothing magic like looking up IDs when the URL contains only a screen name (e.g. the Instagram API requires you to send the user ID almost always while you at first only know their screen name).

Test if all your favicons exist

When you don't only have a favicon.ico in your project but also PNGs of different sizes and backgrounds, you should test if all those files are actually reachable.

Here are a few selectors to get you started:

    'link[rel~="icon"]' # regular ones, matches "shortcut icon" and "icon"
    'link[rel="apple-touch-icon"]' # iOS
    'meta[content][name="msapplication-TileImage"]' # IE11
    'meta[content][name^="msapplication-square"]' # IE11

A s...

jQuery and cross domain AJAX requests

When making cross-domain AJAX requests with jQuery (using CORS or xdomain or similar), you will run into issues with HTTP headers:

  • jQuery will not set the X-Requested-With header. On your server, requests will not look like AJAX requests (request.xhr? will be false).
  • jquery-ujs will not set CSRF headers.

This is by design and improves secu...

Howto respond html or json in the same controller action with Rails 2

Code snippet tested with Rails 2.3

  def index
    # ...
    if request.xhr?
      html = render_to_string(:partial => "list", :layout => false)
      respond_to do |format|
        format.html { render :text => html }
        format.json { render :json => {:html => html, ... } }
      end
    end
  end

Note: Perhaps you ran into ActionView::MissingTemplate error and this card might help. If you call render_to_string within the format.json block, Rails will only look for an index.json template, but not for an `index.erb...

jpillora/xdomain ยท GitHub

Automagically makes XHR requests work cross-domain by tunneling all communications through an IFRAME on your page.

Note sure if it's a wise idea, but it's a thing now.

Working around OpenSSL::SSL::SSLErrors

If your requests blow up in Ruby or CURL, the server you're connecting to might only support requests with older SSL/TLS versions.

You might get an error like: OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=unknown state

SSL Server Test

This SSL Server Test can help finding out which SSL/TLS versions the server can handle.

Ruby

In Ruby, you can teach Net::HTTP to use a specific SSL/TLS version.

uri = URI.parse(url)

ssl_options = {
   use_ssl: true,
   ssl_version...

JavaScript: Calling a function with a variable number of arguments

This card describes how to pass an array with multiple element to a JavaScript function, so that the first array element becomes the first function argument, the second element becomes the second argument, etc.

Note how this is different from passing the entire array as the first argument. Compare these two different ways of calling fun() in Ruby:

# Ruby
array = [1, 2, 3]
fun(array)  # same as fun([1, 2, 3]) (1 argument)
fun(*array) # same as fun(1, 2, 3)   (3 arguments)

Depending on your culture the spreading of array eleme...

whenever: Make runner commands use bundle exec

In whenever you can schedule Ruby code directly like so:

every 1.day, :at => '4:30 am' do
  runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end

Combined with the best practice to hide background tasks behind a single static methods you can test, this is probably preferable to defining additional Rake tasks.

Unfortunately when whenever register a runner command, it doesn't use bundle exec in the resulting crontab. This gets you errors like this:

`gem_original_require': no suc...

Telling Spring to watch certain directories/files

If you have some file or directory that should trigger a Spring reboot, tell Spring e.g. in config/spring.rb:

Spring.watch 'file.rb'
Spring.watch 'lib/templates'

However, Spring will silently drop paths that do not exist at the time calling #watch. Unless you restart Spring (thereby reloading the watch commands), it won't even watch them once they do exist.

Make sure the watchable paths exist before telling Spring to watch, e.g. with

FileUtils.touch 'file.rb'
FileUtils.mkdir_p 'lib/templates'
Spring.wa...

Tearing Down Capybara Tests of AJAX Pages

An all-in-approach to fix the problem of pending AJAX requests dying in the browser when the server ends a test or switches scenarios.


We were able to work around this issue in most projects by doing this instead:

After '@javascript' do
  step 'I wait for the page to load'
end

rbenv: How to update list of available Ruby versions on Linux

When you tell rbenv to install a Ruby it does not know about, you will get an error message.

$ rbenv install 2.1.2
ruby-build: definition not found: 2.1.2

You can list all available versions with `rbenv install --list'.

If the version you're looking for is not present, first try upgrading
ruby-build. If it's still missing, open a request on the ruby-build
issue tracker: https://github.com/sstephenson/ruby-build/issues

(Fun fact: Recent versions of ruby-build will give you a more helpful error message which...

Offtopic: Floppy-disc OS

MenuetOS is an Operating System in development for the PC written entirely in 32/64 bit assembly language. Menuet64 is released under License and Menuet32 under GPL. Menuet supports 32/64 bit x86 assembly programming for smaller, faster and less resource hungry applications.

  • Fits on a single floppy, boots also from CD and USB drives
  • Responsive GUI with resolutions up to 1920x1080, 16 million colours
  • Free-form, transparent and skinnable application windows, drag'n drop
  • SMP multiprocessor support with currently up to 8 cpus
  • IDE: E...

Restangular: How to remove an element from a collection without breaking restangular

So you have a restangular collection and you want to remove an element from it, after you've successfully deleted it from the server.

The README suggests to say something like $scope.users = _.without($scope.users, user). While that works at first glance (the element is no longer in your collection), it will break horribly when you want to use restangular's attributes on that collection.

This...

better rails app restart with the passenger restart-app tool

With this command you can initiate an application restart without touching restart.txt. Unlike touching restart.txt, this tool initiates the restart immediately instead of on the next request. http://blog.phusion.nl/2014/01/02/phusion-passenger-4-0-33-released/

If you want to use this with capistrano 2.x just replace the touch command:

-    run "touch #{current_path}/tmp/restart.txt"
+    run "passenger-config restart-app --ignore-app-not-running #{deploy_to}...

Rails 2: Refuse response formats application-wide

If you regularly get ActionView::MissingTemplate exceptions, maybe some bot visits your site requesting silly formats like:

http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'

Just restrict accepted format parameters for the whole application like this:

class ApplicationController < ActionController::Base

  before_filter :refuse_silly_formats

  private

  def refuse_silly_formats
    acceptable_formats = %w[html xml pdf]

    if par...

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.

How to simulate limited bandwidth in Google Chrome and Firefox

Your development machine is usually on a very good network connection.
To test how your application behaves on a slow network (e.g. mobile), you can simulate limited bandwidth.

Chrome

  • Open the dev tools (Ctrl+Shift+I or F12) and switch to the "Network" tab
  • In the row below the dev tool tabs, there's a throttling dropdown which reads "Online" by default.
  • Inside the dropdown, you will find a few presets and an option to add your own download/upload/latency settings.

Firefox

  • Open the dev tools (Ctrl+Shift+I or F12) and switc...

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.

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