Send mail after capistrano deployment

Posted by Bhushan Ahire | Posted in capistrano, Rails | Posted on 07-05-2008

0

I got a very good plugin at http://code.google.com/p/capistrano-mailer/.
Just copied the details below to have use in future.

It is a Capistrano Plugin AND a Rails Plugin

Ever wanted to be emailed whenever someone on the team does a cap deploy of trunk or some tag to some server. Wouldn’t it be nice to know about it every time a release was deployed? For large rails projects this type of coordination is essential, and this plugin makes sure everyone on the need to know list is notified when something new is deployed.

This plugin is an extension to Capistrano.

That means it registers itself with Capistrano as a plugin and is therefore available to call in your recipes.

If you are looking to roll your own email integration into capistrano then try this pastie: http://pastie.org/146264 (thanks to Mislav Marohni?). But if you want to take the easy road to riches then keep reading ;)

– figurative “riches” of course, I promise nothing in return for your using this plugin

Requirements

  • Rails 2.0.2
  • Capistrano 2.1.0 – 2.2.0

Installation

./script/plugin install http://capistrano-mailer.googlecode.com/svn/trunk/capistrano_mailer

Usage

1. Install the plugin.

2. Add this line to the top of your deploy.rb:

require 'vendor/plugins/capistrano_mailer/lib/capistrano_mailer'

3. Add a cap_mailer_settings.rb file to your config/ directory:

require 'vendor/plugins/capistrano_mailer/lib/cap_mailer'

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address        => "mail.default.com",
:port           => 25,
:domain         => 'default.com',
:perform_deliveries => true,
:user_name      => "releases@default.com",
:password       => "mypassword",
:authentication => :login }
ActionMailer::Base.default_charset = "latin1"

CapMailer.template_root = "vendor/plugins/capistrano_mailer/views/"
CapMailer.recipient_addresses = ["dev1@default.com"]
CapMailer.sender_address = %("Capistrano Deployment" <releases@default.com>)
CapMailer.email_prefix = "[MYSITE-CAP-DEPLOY]"
CapMailer.site_name = "MySite.com"
CapMailer.email_content_type = "text/html"

4. Add these two tasks to your deploy.rb:

namespace :show do
desc "Show some internal Cap-Fu: What's mah NAYM?!?"
task :me do
set :command, task_call_frames.first.task.fully_qualified_name
puts "Running #{command} task"
end
end

namespace :deploy do
...

desc "Send email notification of deployment"
task :notify, :roles => :app do
show.me
mailer.send(rails_env, repository, command, deploy_to, host)
end

...
end

Make sure you’ve defined rails_env, repository, deploy_to and host. command is defined by the show:me task above.

The only required parameters to mailer.send are rails_env, repository, command and deploy_to. The complete set of possible parameters is:

mailer.send(rails_env, repository, command, deploy_to, host = nil, ip_address = nil, output = nil)

If anyone has a cool way of recording the output into a capistrano accessible variable, so that it can be shoved into the release email that would be an excellent contribution!

5. Then add the hook somewhere in your deploy.rb:

after "deploy", "deploy:notify"

6. Enjoy and Happy Capping!

Rails active_record_store & Segmentation fault

Posted by Bhushan Ahire | Posted in Rails, Security | Posted on 25-02-2008

0

Here’s a quick tip if you’re getting errors like this one in your Rails application:

/usr/local/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/session/active_record_store.rb:84: [BUG] Segmentation fault

The most probable reason you’re getting the Segmentation fault and your server crashes is because you’re trying to store too much data in sessions table of your application (I assume you are using active_record_store as a session store).

The problem with “too much data” is that by default, the session table creation rake task created the following migration in Rails 1.x:

class AddSessions < ActiveRecord::Migration
def self.up

create_table :sessions do |t|
t.column :session_id, :string
t.column :data, :text
t.column :updated_at, :datetime
end
add_index :sessions, :session_id
end

def self.down

drop_table :sessions
end
end

Please note the data field defined as text. This means that it can only store up to 64Kb of data. And that also means that if you’re trying to store more than 64Kb in your session.

In order to fix the problem, you just need to manually change the column type before you run migration which creates session store, or just create a new migration which changes parameters of the data column in existing sessions table:

Should look something like that (Rails 2 syntax):

class CreateSessions < ActiveRecord::Migration
def self.up

drop_table :sessions

create_table :sessions do |t|
t.string :session_id, :null => false
t.column :data, :binary, :limit => 10.megabyte
t.timestamps
end

add_index :sessions, :session_id
add_index :sessions, :updated_at
end

def self.down
drop_table :sessions
end
end

Empty your sessions table, restart your server and you’re done. No more segmentation faults. Of course you shouldn’t store that much data in a session in the first place.

Ruby On Rails Security Guide

Posted by Bhushan Ahire | Posted in Rails, ruby, Security | Posted on 08-02-2008

1

Ruby on Rails does a decent job in handling security concerns in the background. You will have to configure your application to avoid few security attacks while plugins would be required for many security concerns which are not at all or poorly managed by rails.

Authentication

Authentication is the foremost requirement of most of the web applications to authenticate and give privileges to their users. Apart from normal authentication mechanism rails have plugins for OpenID, CAS and Access Control. Build your own authentication system only if your requirements are very unique or you do not trust other implementations.

Plugin – Restful Authentication (recommended) – easy to use and you can tweak it according to your requirements.

Build your own authentication. You should rarely need to do this … Restful Authentication is quite flexible.

OpenID – a universal authentication system to avoid use of multiple username and password on the Internet. OpenID is getting quite famous now-a-days.

Access Control : To easily proivde different priviliges to your users. There are a lot of cool plugins available for access control.

Centralized Authentication Server – is used to implement single login/password for your users across multiple application. It can also be used for a single sign-on system. For example, Gmail and Google Reader have a single sign-on between them.

Use Google Authentication API to let your users login using their google username and password.

More Plugins :

- Model -

SQL Injection

The problem arises when metacharacters are injected into your queries to database. Rails has a very good support to avoid SQL injection if you follow conventions in issuing queries to your database.

Description :

Alternate Solution – use hash for specifying conditions in #find

Activerecord Validation

To validate the contents of model object before records are created/modified in the database. Activerecord validations are very useful over database data-type constraints to ensure values entered into the database follow your rules. You might have javascript validations for forms but javascript can easily be switched off. Use javascript validations only for better user experience.

Description :

Conditional validation using :o n and :if options. Checkout this cool video

Be careful using validates_uniqueness_of, it has problems when used with :scope option. Open bug tickets :

Use :allow_blank to pass validations if value is nil or empty string

Testing Validations – do read the comments in this article

Useful Tips

  • Its easy to manage ‘nil’ values using :allow_nil, its quite handy. For ex: set :allow_nil => true in validates_uniqueness_of to check uniqueness of non-nil values and ignore nil values
  • validates_presence_of is not required if you are using validates_format_of, unless regular expression accepts empty string.

Creating records directly from parameters

While creating database records directly from form params, a malicious user can add extra fields into the params and manually submit the web page which will set values of fields which you do not want user to set.

Description :

Alternate Solution – Trim the parameters to keep the required keys and remove the others.

- Controller -

Exposing methods

Use private and protected in controller for methods which should not be actions. Actions are pubic methods and can be invoked from the browser.

hide_action : If non-action controller methods must be public, hide them using hide_action.

Be careful of bypassing private and protected using meta-programming

Authorize parameters

Always authorize user request. By tweaking form parameters or url a user can send request to view/modify other users information if there is no proper authorization of parameters.

For example :

## To find information of an order which belongs to a particular user.

#Incorrect :
@order = Order.find(order_id)

#Correct :
@order = @user.orders.find(order_id)

Do not ignore hidden fields – a user can easily modify their value, so suspect them similar to params[:id]

Filter sensitive logs

Prevent logs of sensitive unencrypted data using #filter_parameter_logging in controller. The default behavior is to log request parameters in production as well as development environment, and you would not like logging of password, credit card number, etc.

Video Tutorial

Cross Site Reference(or Request) Forgery (CSRF)

In a CSRF attack, the attacker makes victim click on a link of his choice which would contain a GET/POST request and causes web application to take malicious action. The link could be embedded in a iframe or an img tag. Its recommended to use secret token while communicating with user to avoid this attack.

Its little complex to understand this attack. So, only those readers who are very enthusiastic to know about it, please read the Description below. Rest can directly move ahead to use the plugin.

Description :

Use Get and Post appropiately (note : Both get and post are vulnerable to CSRF)

Example – Gmail CSRF security flaw

Plugin – CSRF Killer (recommended) – it requires edge rails

Minimize session attacks

If an attacker has session-id of your user, he can create HTTP requests to access user account. An attacker can get session-id by direct access to user machine or is able to successfully run malicious scripts at user machine. In this section we will talk about how to avoid or minimize the risk if attacker has user session-id. Following steps are helpful:

  1. Store IP Address, but creates problem if user moves from one network to another.
  2. Create a new session everytime someone logs in.
  3. Expire session on user logout, user is idle for a time period or on closing of browser/tab. For maximum security expire sessions on all the three conditions.

Code for session expiry on timeout

## Timeout after inactivity of one hour.
MAX_SESSION_PERIOD = 3600
before_filter :session_expiry
def session_expiry
   reset_session if session[:expiry_time] and session[:expiry_time] < Time.now
   session[:expiry_time] = MAX_SESSION_PERIOD.seconds.from_now
   return true
end

Plugin – Session Expiration for session expiry on timeout

Do not put expiry time in the cookie unless your cookie information is properly encrypted. If not, use server side session expiry.

Persistent session / login in rails – global setting in enviornment.rb


ActionController::Base.session_options[:session_expires] = <i>say after two years</i>

Persistent session / login in rails – to give your users a feature – remember me

Stop spam on your website from DNS Blacklist

Avoid access to your website from IP addresses which are present in DNS Blacklist(DNSBL).

Plugin – DNSBL check

Caching authenticated pages

Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.

- View -

Cross site scripting(XSS) attack

Cross Site Scripting is a technique found in web applications which allow code injection by malicious web users into the web pages viewed by other users. An attacker can steal login of your user by stealing his cookie. The most common method of attack is to place javascript code on a website that can receive the session cookie. To avoid the attack, escape HTML meta characters which will avoid execution of malicious Javascript code. Ruby on Rails has inbuilt methods like escape_html() (h()), url_encode(), sanatize(), etc to escape HTML meta characters.

Description

Can we avoid tedious use of h() in views?

Sanitize() is used to escape script tags and other malicious content other than html tags. Avoid using it … its unsecure. Use white_list instead.

White_list plugin

Anti-spam form protection

Use Captcha or Javascript based form protection techniques to ensure only human can submit forms successfully.

When using Captcha do ensure the following :

  1. Images are rendered on webpage using send_data and are not stored at the server, because its not required to store images and are redundant.
  2. Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.
  3. Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.

Tutorial – a nice article on concepts of captcha

Plugin – ReCaptcha (recommended)

Plugin – BrainBuster – a logic captcha based on simple puzzles, math and word problems. By default, it has limited set of problems and you would have to come up with large set of your own problems.

Plugin – Simple Captcha (not recommended) as it breaks all the must have features of a good Captcha implementation.

For less critical systems like blogs, a more user-friendly option can be use of CSS based technique or JavaScript based plugin unlike Captcha. Both JavaScript and CSS based techniques can only avoid spam from dumb or general bots. If an hacker specifically targets your site or bot is smart enough, you are dead, so be careful.

Captcha with Multiple Servers

Hide mailto links

Mailto links in a webpage can be attacked by e-mail harvesting bots. Use the plugin CipherMail to generate a 1024 bit random key and obfuscate the mailto link.

Plugin – CipherMail

Use password strength evaluators

A lot of people have used password strength evaluators simply because its used by google in their registration form. You can use it to help your users register with strong password. But I don’t think its a must have security addon. Uptill now I have not found a good algorithm to assess strength of a password, but some of them are reasonable.

Also, if there is an open source tool or algorithm for evaluating password strength, it can easily be broken. So, you might consider tweaking the algorithm or building one from scratch.

Tools

- Miscellaneous -

Transmission of Sensitive information

Use SSL to encrypt sensitive data between transfer from client to server. SSL hits server performace, so you might consider using SSL only for few pages which transfer sensitive data to and fro.

Plugin ssl_requirement

Mongrel, rails, apache and SSL

Controller in SSL subdomain

Sample SSL code in rails

File upload

Be very careful when you allow your users to upload files and make them available for other users to download.

Description

Must read – Section 26.7 of Agile web development with rails – 2nd edition

In place file upload

3 plugins for file upload reviewed at :

Secure your setup / environment

Proper Mysql configuration

Use good passwords

Security plugins directory

Original Source http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide

10-Minute Quick Start Guide for Facebooker – Create a Facebook App Using Rails in 7 Easy Steps

Posted by Bhushan Ahire | Posted in Rails | Posted on 04-02-2008

0

Here I found a gr8 post by Gerald Bauer (RailsAdvance), Thanks for gr8 post.

Welcome to the 10-Minute Quick Start Guide for Facebooker showing you how to create a Facebook application from scratch using Ruby on Rails in 7 easy steps:

  1. Create a Rails application
  2. Install the Facebooker Rails plugin
  3. Log on to Facebook and set up a new application
  4. Add your API key and secret to the facebooker.yml configuration file
  5. Create Rails controller (and view skeletons)
  6. Configure default route and remove public/index.html page
  7. Use Facebooker to get your name, profile pic and status

Continue reading

Acts_as_nested_set ActiveRecord rendered with mx:Tree in Flex

Posted by Bhushan Ahire | Posted in Rails | Posted on 29-01-2008

0

Gr8 post by Daniel Wanja for Use acts_as_nested_set with Flex.

ActiveRecord: app/models/category.rb

 

app/models/category.rb

class Category < ActiveRecord::Base
  acts_as_nested_set
end

Controller: app/controllers/categories_controller.rb

 

app/controllers/categories_controller.rb

class CategoriesController < ApplicationController
  def index
     Category.result_to_attributes_xml(Category.root.full_set)

  end
end

Flex Application: ActsAsNestedSet.mxml

 

ActsAsNestedSet.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="vertical"
    applicationComplete="categories.send()">
<mx:HTTPService id="categories" url="http://localhost:3000/categories" resultFormat="e4x" />
<mx:Tree dataProvider="{categories.lastResult}"
    labelField="@name"
    width="100%" height="100%" />
</mx:Application>

Result:
20071123_categories.jpg

XML generated by Category.result_to_attributes_xml(Category.root.full_set):

 

XML generated by Category.result_to_attributes_xml(Category.root.full_set)

<node name="Main Category" id="15" description="">

  <node name="Cameras & Photo" id="16" description="">

    <node name="Bags" id="17" description=""/>
    <node name="Accessories" id="18" description=""/>

    <node name="Analog Cameras" id="19" description=""/>
    <node name="Digital Cameras" id="20" description=""/>

  </node>
  <node name="Cell Phones" id="21" description="">

    <node name="Accessories" id="22" description=""/>
    <node name="Phones" id="23" description=""/>

    <node name="Prepaid Cards" id="24" description=""/>
  </node>

  <node name="Dvds" id="25" description="">
    <node name="Blueray" id="26" description=""/>

    <node name="HD DVD" id="27" description=""/>
    <node name="DVD" id="28" description=""/>

  </node>
</node>

I used the http://wiki.rubyonrails.org/rails/pages/BetterNestedSet plugin.

Too cool!

Rails REST meets Rails 2.0

Posted by Bhushan Ahire | Posted in Rails | Posted on 29-01-2008

2

Hey, I got a very good post posted by Jeff on http://www.softiesonrails.com/.
I think this will be helpful to me and all rails developers who uses Rails 2.0 which is most REST oriented

We developed those articles when 1.2 was a mature, stable release, and when it had also become clear that 2.0 would not significantly change what had already been achieved in 1.2.

However, Rails 2.0 did fine-tune the way we develop RESTful applications in Rails, prompting us to add one more article and bring the series up to date.

REST Refresher

Let’s review what we covered in the first five articles:

  1. When deciding what controllers you need, think in terms of resources.
  2. Don’t think twice about what actions your controllers should have. Use the Golden Seven for each resource: index, new, edit, create, show, update, delete.
  3. A resource maps to Rails controller, not necessarily to an underlying model.
  4. Deliver your resources in a way that’s appropriate to the user’s experience. Some users want HTML, some want RSS, some want audio, some have big screens, some have tiny cell phone screens, some want to use your application like a web service and expect XML to be returned.
  5. The client application will indicate their preference with the “Accept” header in the http request. Use respond_to in your controller to automatically map the Accept header to your response.

Once you’ve identified a resource that you want to implement, you just need to implement it RESTfully in Rails.

The Hard Way

I can’t believe I’m saying that anything in Rails is actually hard, but if there is a “hard” way to write RESTful code, this would be it (“by hand” is more precise, I suppose). Here’s the recipe:

1. If your resource needs a supporting model, use script/generate model <resource-name> (or ruby scriptgenerate model on Windows). You can now specify any columns you already know your model needs right on the command line, which will give you a nice head start in your migration file.

Don’t forget to rake db:migrate before you start running your tests (you thought I was going to say “running your app”, didn’t you?)

script/generate model Airport city:string identifier:string

2. Generate a nice empty controller with script/generate controller <resource-name> and fill it with the standard seven actions.

script/generate controller Airports

Using textmate? You can steal our Textmate snippet to quickly write all the boilerplate code for you.

3. Create views only for the actions that need them, typically these are:

  • index.html.erb
  • new.html.erb
  • edit.html.erb
  • update.html.erb
  • show.html.erb

In Rails 2.0, the middle part of the template filename maps to the HTTP mime type (more or less), so you might also have files named index.iphone.erb or show.xml.builder.

Also, be sure to learn the cool new form_for syntax in Rails 2.0 that automatically generates the right target url based on whether you give it a new object (which will target the create action) or one that’s already been saved to the database (which will target the update action).

In fact for a nice overview of all that’s new in Rails 2.0, we recommend the PeepCode Rails 2.0 PDF by Ryan Daigle (disclaimer: PeepCode supports this blog.) Ryan’s blog is also an excellent way to keep up on all the new stuff in Rails.

4. Add a map.resources line to your routing file. There are lots of options here, but the simplest looks like:

map.resources :airports

This will generate a package of handy named routes, map incoming action/verb pairs to the right controller action, and automatically ensure that actions like create, update and delete only respond to POST verbs only.

But you knew all this already – it’s been around since Rails 1.2.

5. Always, always, always try to use named routes whenever you use link_to and any other helper method that expects a hash of url options. The syntax of named paths has changed somewhat in 2.0 to make it easier to construct links for the most typical scenarios. Check the Rails API docs and use the new rake routes task as a cheat sheet whenever you need it.

Help Rails Help You

Ok, now for what’s new in Rails 2.0 that can make this process much easier.

Rails 2.0 has two built-in generators to make your RESTful life easier.

1. Generating A Resource Without Views

If you have a model underpinning your resource, you can get 80% of the way done by using the totally awesome resource generator (again, available since Rails 1.2, but somehow few people know about it). It’s syntax is identical to the model generator, but it will also create a RESTful controller with the Golden Seven actions and add a map.resources line for you.

script/generate resource Airport city:string identifier:string

So what was the other 20%? The views are not generated for you.

2. Generating Everything With The Scaffold Generator

You can inch up to 95% of the way for the simplest situations by using the new scaffold generator.

Ok, time out.

We’ve always said that the scaffold generator was bad. Very bad.

So now we’re recommending it?

Not if you’re using 1.2.x or earlier. In that case, do not use the scaffold generator. If you’re using 1.2, you can use the scaffold_resource generator instead.

But in Rails 2.0, the scaffold generator is no longer evil, it is downright righteous. It will create the model, controller, routes, and view scaffolding that demonstrates how to use the new form_for syntax. Very cool stuff. Again, it uses the model generator syntax, so use the singular form of your resource and specify any columns you already know up front:

script/generate scaffold Airport city:string identifier:string

You’ll end up rewriting the views to truly fit your application, but that’s the whole idea. It’s scaffolding, not the real thing, silly.

If you’ve used the resource generator and now want the scaffolded views as well, you’re in luck: Brian Hogan has released a gem to do just that for you.

(Oh, and I know we had you at “easier.”)

Ok, NOW we’re done

We hope this wraps up our REST series. At least for now.

Deploying two rails application with Apache + mongrel on windows

Posted by Bhushan Ahire | Posted in Rails | Posted on 28-01-2008

1

Install Ruby, Gems and then install Ruby on Rails:



sudo gem install rails --include-dependencies

Now download and install Apache 2.2 using, as the fastest way, the msi package.

Now enable the needed modules (url rewriting, proxy, proxy_balancer e proxy_http) by editing the httpd.conf file (under c:Apache_Software_FoundationApache2.2conf, if you installed Apache in its standard path). You just need to uncomment the following lines (remove the #):



LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Install the mongrel and mongrel_service gems:



gem install mongrel (pick last version for win32)
gem install mongrel_service (pick last version for win32)

Now we will create a mongrel cluster of 2 windows services responding at http://127.0.0.1 on ports 3010, 3011 serving a rail application at the path c:wwwrormyapp that will be started from the windows system user. The two windows services will be respectively named mongrel_myapp1 and mongrel_myapp2. Open the command prompt and type:



mongrel_rails service::install -N mongrel_myapp1 -p 3010 -e production -c c:wwwrormyapp
mongrel_rails service::install -N mongrel_myapp2 -p 3011 -e production -c c:wwwrormyapp

Now open the windows services tool, make the 2 new services have an automatic startup type (so they will still be started when you reboot).
Test if your application is now running at the two ports:



http://localhost:3010

http://localhost:3011

If everything is working fine, you are ready to place Apache in front of these 2 mongrel services, to manage the load balancing of you application.

The best way to configure Apache is to create a Virtual Host for your ROR application. First edit your httpd.conf file, and uncomment the following line:



# Virtual hosts

Include conf/extra/httpd-vhosts.conf

Now edit the httpd-vhosts.conf file, like this (keep the slashes in the *nix fashion!):



NameVirtualHost *:80

#Proxy balancer section (create one for each ruby app cluster)
<Proxy balancer://myapp_cluster>
  BalancerMember http://myapp:3010
  BalancerMember http://myapp:3011
</Proxy>

#Virtual host section (create one for each ruby app you need to publish)

<VirtualHost *:80>
  ServerName myapp
  DocumentRoot c:/www/ror/myapp/public/

  <Directory c:/www/ror/myapp/public/ >
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
  </Directory>

  #log files
  ErrorLog /var/log/apache2/myapp_error.log
  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
  CustomLog /var/log/apache2/myapp_access.log combined

  #Rewrite stuff
   RewriteEngine On

  # Check for maintenance file and redirect all requests
  RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
  RewriteCond %{SCRIPT_FILENAME} !maintenance.html
  RewriteRule ^.*$ /system/maintenance.html [L]

  # Rewrite index to check for static
  RewriteRule ^/$ /index.html [QSA]

  # Rewrite to check for Rails cached page
  RewriteRule ^([^.]+)$ $1.html [QSA]

  # Redirect all non-static requests to cluster
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://myapp_cluster%{REQUEST_URI} [P,QSA,L]

</VirtualHost>

Add your app as a host in hosts.file (in the c:WINNTsystem32driversetc folder):



127.0.0.1 localhost
127.0.0.1 myapp

Restart now Apache from the Windows services panel, and if everything is fine you should have your app served by Apache at the following url:

http://myapp

Add sql session store to rails application

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

Only Mysql, Postgres and Oracle are currently supported (others work, but
you won’t see much performance improvement).

Step 1

If you have generated your sessions table using rake db:sessions:create, go
to Step 2

If you’re using an old version of sql_session_store, run

    script/generate sql_session_store DB

where DB is mysql, postgresql or oracle

Then run

    rake migrate

or

    rake db:migrate

for edge rails.

Step 2

Add the code below after the initializer config section:

    ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.
      update(:database_manager => SqlSessionStore)

Finally, depending on your database type, add

    SqlSessionStore.session_class = MysqlSession

or

    SqlSessionStore.session_class = PostgresqlSession

or

    SqlSessionStore.session_class = OracleSession

after the initializer section in environment.rb

Step 3 (optional)

If you want to use a database separate from your default one to store your
sessions, specify a configuration in your database.yml file (say sessions),
and establish the connection on SqlSession in environment.rb:

   SqlSession.establish_connection :sessions

IMPORTANT NOTES

  1. The class name SQLSessionStore has changed to SqlSessionStore to let Rails
    work its autoload magic.
  2. You will need the binary drivers for Mysql or Postgresql. These have been
    verified to work:

    • ruby-postgres (0.7.1.2005.12.21) with postgreql 8.1
    • ruby-mysql 2.7.1 with Mysql 4.1
    • ruby-mysql 2.7.2 with Mysql 5.0

Add + in URL insteade of space (%20)

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

This is a workaround to get spaces in URL as pluses not %20 like it is in Rails2.

module ActionController::Routing
  class DynamicSegment
    def interpolation_chunk
      "#{CGI.escape(#{local_name}.to_s)}"

    end

    def match_extraction(next_capture)
      default_value = default ? default.inspect : nil

      %[
        value = if (m = match[#{next_capture}])
          CGI.unescape(m)
        else

          #{default_value}
        end
        params[:#{key}] = value if value
      ]
    end

  end
end

Shorcuts for kill and restart rails server

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

More lovely alias commands… this time to kill/restart Rail’s script/server from any Terminal session or login on your box… (as long as your the same user).

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'