Monday, October 13, 2014

Route Globbing In Ruby on Rails

Route globbing is a way to specify parameter from request should be matched to all remaining parts of a route. For example in Rails 4:

get 'users/*xyz' => 'users#list'

When client send GET request with URL '/users/foo/bar', Rails will automatically match to action list in controller users with params[:xyz] equals 'foo/bar'. The fragments prefixed with a star are called "wildcard segments".

Wildcard segments can contain request format. For example, By requesting '/users/foo/bar.json', params[:xyz] will equals 'foo/bar' with request format of JSON. If you want to make the format segment must be exist, in config/routes.rb you can supply format: true like this:

get 'users/*xyz' => 'users#list', format: true

A route have more than one wildcard segments. Wildcard segments can be anywhere and can combine with other parameters. For example:

get '*abc/users/*xyz/:username' => 'users#list'

So, if client make GET request to '/yuhuu/woohoo/users/foo/bar/example' as the result params[:abc] equals 'yuhuu/wohoo', params[:xyz] equals 'foo/bar', and params[:username] equals 'example'

Sunday, April 13, 2014

Linkedin Share Button in Rails 4 with Turbolinks Enabled

While implementing Linkedin share-button on my Rails 4 application with Turbolinks enabled, I encounter problem how to reload Linkedin share-button correctly because my code always showing "duplicate in.js loaded, any parameters will be ignored".

Friday, November 15, 2013

Javascript Alert For Unsaved Changes with Turbolinks, Jquery, And Rails 4

jQuery change event can be used to detect form change. But because Turbolinks pages will change without full reload, we can't rely on DOMContentLoaded or jQuery.ready() to trigger change event. Here is how to write jQuery change event code with Turbolinks enabled. Tested with Rails 4.0.0.

# Coffeescript

ready = >
  # your jquery code
  # ...

# page:load is fired at the end of the loading process.
$(document).ready(ready)
$(document).on('page:load', ready)

change = ->
  $("form input, form textarea").change( ->
    $('a').click( ->
      confirm('Unsaved changes on the page. Are you sure?')
    )
  )

$(document).ready(change)

# the page has been parsed and changed to the new version and on DOMContentLoaded
$(document).on('page:change', change)


# Javascript

# ...
change = function() {
  $("form input, form textarea").change(function() {
    $('a').click(function() {
      confirm('Unsaved changes on the page. Are you sure?');
    });
  });
}; 
# ...


Gist: https://gist.github.com/kuntoaji/7472721