Register now and start sharing your code snippets.
-->

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

HTML (Rails) posted 6 months ago by christian

   1  <input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden" />

or

   1  <%= token_tag %> 

Tagged authenticity, token, ruby, rails

How to install and use the Sphinx search engine and acts_as_sphinx plugin on Debian Etch

Shell Script (Bash) posted 7 months ago by christian

Inspiration for this snippet was taken from this post on the Sphinx forum, plus this blog post.

Compiling Sphinx

First install the prerequisites:

   1  sudo aptitude install libmysql++-dev libmysqlclient15-dev checkinstall

Next download sphinx, libstemmer and install everything and the fish:

   1  cd /usr/local/src
   2  
   3  wget http://sphinxsearch.com/downloads/sphinx-0.9.8-rc2.tar.gz
   4  tar zxvf sphinx-0.9.8-rc2.tar.gz 
   5  
   6  cd sphinx-0.9.8-rc2/
   7  
   8  # Add stemming support for Swedish, Finnish and other fun languages.
   9  wget http://snowball.tartarus.org/dist/libstemmer_c.tgz
  10  tar zxvf libstemmer_c.tgz
  11  
  12  ./configure --with-libstemmer
  13  make
  14  
  15  make install

Configure Sphinx

Create a sphinx.conf file in your Rails config directory, as described here, or use this template.

Install acts_as_sphinx plugin

   1  ./script/plugin install http://svn.datanoise.com/acts_as_sphinx

Add acts_as_sphinx to your model:

   1  class Documents
   2     acts_as_sphinx
   3  end

Indexing content

   1  rake sphinx:index
   2  
   3  (in /var/www/xxx.com/releases/20080429144230)
   4  Sphinx 0.9.8-rc2 (r1234)
   5  Copyright (c) 2001-2008, Andrew Aksyonoff
   6  
   7  using config file './sphinx.conf'...
   8  indexing index 'xxx.com'...
   9  collected 5077 docs, 0.6 MB
  10  sorted 0.1 Mhits, 100.0% done
  11  total 5077 docs, 632096 bytes
  12  total 0.160 sec, 3950427.25 bytes/sec, 31729.86 docs/sec

Reindexing content

sphinx:index shouldn’t be run while the searchd process is running, so use rake sphinx:rotate instead, which restarts the searchd process after indexing.

Starting the daemon

   1  mkdir -m 664 /var/log/sphinx
   2  rake sphinx:start
   3  
   4  (in /var/www/xxx.com/releases/20080429144230)
   5  Sphinx 0.9.8-rc2 (r1234)
   6  Copyright (c) 2001-2008, Andrew Aksyonoff
   7  
   8  using config file './sphinx.conf'...
   9  Sphinx searchd server started.

Searching

   1  Documents.find_with_sphinx 'why did I write this'

Tagged sphinx, search, acts_as_sphinx, debian, etch, rails, install, libstemmer

Rolling back database migration one step in Rails

Ruby posted 7 months ago by marko

I found this awesome trick to rollback a Rails database migration one step. Add the following code to Rakefile.

   1  namespace :db do
   2    desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
   3    task :rollback => :environment do
   4      step = ENV['STEP'] ? ENV['STEP'].to_i : 1
   5      version = ActiveRecord::Migrator.current_version - step
   6      ActiveRecord::Migrator.migrate('db/migrate/', version)
   7    end
   8  end

And roll back with a breeze.

   1  rake db:migrate
   2  rake db:rollback

Tagged rails, active record migration

Installing ImageMagick, mini-magick and rmagick on Mac OS X Leopard

Ruby posted 8 months ago by christian

I had no success installing ImageMagick and mini-magick with the instructions I found on this page but after some googling I found this blog post, which had the magic commands that worked for me:

   1  sudo port install tiff -macosx  #disables the linkage with Apple's open gl
   2  sudo port install ImageMagick
   3  
   4  sudo gem install rmagick
   5  sudo gem install mini_magick

To test mini-magick, open an irb console and paste in the following code:

   1  require 'rubygems'
   2  require 'mini_magick'
   3  
   4  path = "public/images/0000/0003/logo.jpg"
   5  image = MiniMagick::Image.new(path)
   6  
   7  #print width and height
   8  puts image[:width]
   9  puts image[:height]

Tagged imagemagick, attachment_fu, rails, ruby, mac, osx, leopard, mini-magick, rmagick

How to add OpenID support to your Rails application with the open_id_authentication plugin

Ruby posted 8 months ago by christian

These instructions have been tested with Rails 2.0.2 and ruby-openid 2.0.4. The snippet is an adaptation of the instructions in Ryan Bates’ screencast on how to integrate OpenID with Rails.

Installing and configuring the restful_authentication plugin

Follow these instructions: How to install and use the restful_authentication Rails plugin.

Installing the ruby-openid gem

   1  gem install ruby-openid

Installing the open_id_authentication Rails plugin

   1  script/plugin source http://svn.techno-weenie.net/projects/plugins/
   2  script/plugin install open_id_authentication

Create the migration files

   1  rake open_id_authentication:db:create

Add the following to the self.up method in 002_add_open_id_authentication_tables.rb:

   1  add_column :users, :identity_url, :string

Configuring the routes

   1  map.open_id_complete 'session', :controller => "sessions", :action => "create", :requirements => { :method => :get }

Protect the identity_url field

Next protect the identity_url field, by adding the following to user.rb, account.rb or your custom user model:

   1  attr_accessible :login, :email, :password, :password_confirmation, :identity_url

Add the following to the self.down method in 002_add_open_id_authentication_tables.rb:

   1  remove_column :users, :identity_url

Integrating Open-id with the login page

Add the following to sessions/new.html.erb:

   1  <label for="openid_url">OpenID URL</label><br />
   2  <%= text_field_tag "openid_url" %>

Make sure you’re showing flash messages, otherwise you won’t see the error messages:

   1  <html>
   2    <head></head>
   3    <body>
   4      <%= [:notice, :error].collect {|type| content_tag('div', flash[type], :id => type) if flash[type] } %>
   5  
   6      <%= yield %>
   7    </body>
   8  </html>

Modifying the sessions controller

Copy & paste the following code in app/controllers/sessions_controller.rb:

   1  class SessionsController < ApplicationController
   2    # Hack to fix: No action responded to show
   3    def show
   4      create
   5    end
   6  
   7    def create
   8      if using_open_id?
   9        open_id_authentication(params[:openid_url])
  10      else
  11        password_authentication(params[:login], params[:password])
  12      end
  13    end
  14  
  15    def destroy
  16      self.current_user.forget_me if logged_in?
  17      cookies.delete :auth_token
  18      reset_session
  19      flash[:notice] = "You have been logged out."
  20      redirect_back_or_default('/')
  21    end
  22  
  23    protected
  24  
  25    def open_id_authentication(openid_url)
  26      authenticate_with_open_id(openid_url, :required => [:nickname, :email]) do |result, identity_url, registration|
  27        if result.successful?
  28          @user = User.find_or_initialize_by_identity_url(identity_url)
  29          if @user.new_record?
  30            @user.login = registration['nickname']
  31            @user.email = registration['email']
  32            @user.save(false)
  33          end
  34          self.current_user = @user
  35          successful_login
  36        else
  37          failed_login result.message
  38        end
  39      end
  40    end
  41  
  42    def password_authentication(login, password)
  43      self.current_user = User.authenticate(login, password)
  44      if logged_in?
  45        successful_login
  46      else
  47        failed_login
  48      end
  49    end
  50  
  51    def failed_login(message = "Authentication failed.")
  52      flash.now[:error] = message
  53      render :action => 'new'
  54    end
  55  
  56    def successful_login
  57      if params[:remember_me] == "1"
  58        self.current_user.remember_me
  59        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
  60      end
  61      redirect_back_or_default('/')
  62      flash[:notice] = "Logged in successfully"
  63    end
  64  end

OpenID authentication from behind a proxy

First, set the HTTP _PROXY environment variable to the proxy URL :

   1  export HTTP_PROXY=http://proxy.aktagon.com:8080/

Then add the following to environment.rb:

   1  OpenID::fetcher_use_env_http_proxy

Tagged openid, authentication, rails, ruby, plugin, restful_authentication