Dimitar Kostov ramblings

XTHML in HAML view in Rails 3

config/initializers/haml.rb
1
Haml::Template.options[:format] = :xhtml
some_view.html.haml
1
2
3
4
5
!!! XML
!!!

-# <?xml version='1.0' encoding='utf-8' ?>
-# <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Converting video clip to gif

# Borrowed from http://schneems.com/post/41104255619/use-gifs-in-your-pull-request-for-good-not-evil

$ ffmpeg -i ScreenFlow.mov -pix_fmt rgb24 output.gif
$ convert -layers Optimize output.gif output_optimized.gif

Passing arguments to rake task

Rakefile
1
2
3
4
5
6
7
namespace :log do
  desc 'Upload logfile to cloud-based server'
  task :upload, [:filename] => [:environment] do |t, args|
    # upload logic
    # args[:filename] is the passed argument
  end
end
$ rake log:upload[development.log]

# If the shell complains just escape the brackets

$ rake log:upload\[development.log\]

Cookie based authentication strategy in Devise

This method assumes that you have token authentication strategy enabled and will use the token for the user for cookie authentication

lib/devise/cookie_token_auth_strategy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Warden::Strategies.add(:token_cookie_strategy) do
  def valid?
    token_from_cookie
  end

  def authenticate!
    if token_from_cookie.present? && (user = User.find_for_token_authentication(:auth_token => token_from_cookie)).present?
      delete_token_from_cookie
      success!(user)
    else
      fail!("Could not log in")
    end
  end

  def token_from_cookie
    cookies[:authentication_token]
  end

  def delete_token_from_cookie
    cookies.delete(:authentication_token)
  end

end
config/initializers/devise.rb
1
2
3
4
5
Devise.setup do |config|
  config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :token_cookie_strategy
  end
end
config/application.rb
1
2
3
4
5
6
module YourApp
  class Application < Rails::Application
    config.autoload_paths += %W(#{config.root}/lib/devise)
    # rest of the file
  end
end

Preserve new lines in Rails i18n

1
2
3
4
5
user:
  mailer:
    footer: |
      Best regards,
      Your Company.
1
2
3
4
5
6
!!!
%html
  %head
    %meta{:content => "text/html; charset=UTF-8"}
  %body
    = simple_format I18n.t('user.mailer.footer')