Archive for the ‘rails’ Category

Single Sign-On In Rails Application

Single sign-on (SSO) is a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. Such as we once log in to google, we are permitted to access the Youtube, Docs, Google Drive etc. dnd1999110501 We may think about sharing the session cookies among the all domains but its generally not a good idea. One can steal cookies to sign in from other system or browser. Single SignOn Helps us in getting around this problem and implement a much robust system. How do we implement Single Sign-On in Rails App? We will try to get our hand around on how to build a prototype around a rails app to implement single sign-on. We will be looking a sample rails application powered by CASino gem Why we are using CASino ?
  1. Distributed under MIT LIcense
  2. Active Development since
  3. External authentication sources (LDAP, SQL)
  4. Two-factor authentication
  5. Session-overview for logged-in users
  6. Full localization support
  7. REST-API
So what is CASino exactly? CASino is a simple Single sign-on server application. It supports the CAS protocol and can therefore be used in combination with almost every web programming language out there. CAS is an authentication system originally created by Yale University to provide a trusted way for an application to authenticate a user. CAS centralizes authentication: It allows all your applications to ask users to login to a single sign-on server The implementation. Here we have two apps client and server. We assume that the app is using devise for the demonstration purposes. The Logic can easily be extended to other authentication methods though. The app is as simple as configuring a few variables in the CASino gem.
  1. user request to client domain .
  2. it redirects to the server if not authorised.
  3. Start with adding the gems client app
  4. redirects to back url to whichever client request url is
Step #1 Implementing the client application. Gemfile # If You face some compatability issues then use ruby 2.1

gem 'devise_cas_authenticatable', git: '<a href="https://github.com/jpamaya/devise_cas_authenticatable">https://github.com/jpamaya/devise_cas_authenticatable</a>'

routes.rb

devise_for :users, skip: [:sessions], controllers: { cas_sessions: 'sso_cas' }

devise_scope :user do

get "sign_in", to: "devise/cas_sessions#new"

delete "sign_out", to: "devise/cas_sessions#destroy"

end

devise.rb # ==> Configuration for SSO server authentication

config.cas_base_url = "http://localhost:4000/"

config.cas_create_user = false

config.cas_destination_logout_param_name = 'service'

config.cas_enable_single_sign_out = true

User.rb

devise :cas_authenticatable

Now run client application on localhost:3000 and begin with typing users/sign_in Since we overwrote devise’s sign in mechanism, so instead of presenting devise’s normal sign in page, we are redirected to localhost:4000 which is the backend app to authenticate the users. Lets prepare the backend app to authenticate the users.  Step #2 Start with implementing code in server app limitation use ruby ruby “2.1.5” and rails “3.2.11” check rails -v ‘~>(‘ 3.2.11′). for server app Gemfile #It users these db to store sessions and some tokens. casino will take care all about these

gem 'sqlite3'   # for sqlite support

gem 'mysql2'    # for mysql support

gem 'pg'        # for postgresql support

gem 'casino'

Run bundle install and rails g casino:install The CAS configuration is stored under config/cas.yml. This is where you configure how your SSO handles logins. An example configuration can be found in the file config/cas.yml.example provide the valid db credentials and run the migrations. Run this app on localhost:4000 , Just follow the old steps
  1. Goto localhost:3000/users/sign_in
  2. You will redirected to localhost:4000 enter credentials click sign in
  3. You will be redirected back on successful login
In the links below you can find some ready made examples for you to clone these  apps and have better understanding of SSO.
Server exampleruby “2.1.5”git clone https://github.com/codescrum/casino-sso-server-example.gitRails 4 client examplegit clone https://github.com/codescrum/casino-sso-client-rails4-example.gitRails 3 client example git clone https://github.com/codescrum/casino-sso-client-rails3-example.git
Let us know in comments if you face any troubles in the implementation !! PS: Single Sign-out has been left as a thought for another day and we will discuss that in a follow up blog.

A Step by Step Guide to Setup Rails application on Ec2 instance (Ubuntu Server)

Sometimes the Bitnami or other Rails AMIs doesn’t fit your needs directly and you will feel the need of building the Server yourself.Here I go step by step in building such a stack on top of Amaon EC2 Ubuntu Server.
  • Rails applications are a little bit different to install on servers but the process is very easy.Rails application needs a web server and an application server to run with. For development, it comes with default Webrick server that serve as application server on local machine. For setting it up on production server, we have the following choices on Web and application servers :-

    • Web servers

      1. Apache

      2. Nginx

    • Application Servers

      1. Passenger

      2. Thin

      3. Puma

      4. Unicorn

  • The simplest and best combination consists of Nginx + Passenger. It allows greater flexibility for configuration and also allows good speed over other combinations. So we are going to setup an Rails application using Nginx + passenger configuration on a bare Ubuntu server. Here are the steps :-

  1. Launch an Ec2 instance with ubuntu AMI. Make sure you have HTTP and SSH access to the server.

  2. SSH into the server by using private key (.pem) used while launching the instance and install the available updates by running :-

    sudo apt-get install updates
  3. Now you need to setup ruby on your server, so install the single user rvm ruby by following this blog.
  4. Load the rvm and make the installed ruby as default by running the following commands :-

    source ~/.rvm/scripts/rvm
    rvm use 2.1.0 –default
  5. Install the version control to clone your rails application to server. We generally use Git with rails application which can be installed by running the following command :-

    sudo apt-get install git
  6. Now clone your application on the server :-

    git clone yourepo.git

    Note:- In case of private git repository, you need to add public key of server to deploy keys of your repository, otherwise you will be promped with an permission denied error.

    OR

    Deploy using application to this server using Capistrano script. Please read this blog for more details on deploying your application using Capistrano.

  7. Now go to your application and install the gems by running bundle install command. If you want to setup your database on the same server, you can do the same by using the following commands 😐

    • In case of MYSQL

      sudo apt-get install mysql-server mysql-client
      sudo apt-get install libmysql++-dev
    • In case of POSTGRESQL, follow this blog for installation and then install the development headers

      sudo apt-get install libpq-dev

      After setting this up, migrate your databases in whichever environment you want to launch the server.

  8. Now install the Passenger gem by running :-

    gem install passenger

  9. Next step is to install the Nginx server, but we have some pre-requisits for this.

      1. It needs curl development headers which can be installed by :-

        sudo apt-get install libcurl4-openssl-dev

      2. It will be installed under /opt directory and your user should have permissions to that folder, so make your user as user owner for /opt directory by :-

        sudo chown -R ubuntu /opt

  10. Now install the Nginx server with passenger extension by running the following command :-

    passenger-install-nginx-module

  11. Set your Nginx server as service in init script by using the following commands :-

    wget -O init-deb.sh http://library.linode.com/assets/660-init-deb.sh
    sudo mv init-deb.sh /etc/init.d/nginx
    sudo chmod  +x /etc/init.d/nginx
    sudo /usr/sbin/update-rc.d -f nginx defaults
  12. Setup your application path in the nginx configuration file i.e. /opt/nginx/conf/nginx.conf.

    server {

    listen 80;

    server_name localhost;

    root /home/ubuntu/my_application/public #<-- be sure to point to 'public'

    passenger_enabled on;

    rails_env production;

    }

  13. Lastly start your server by running the following command :-

    sudo service nginx start

     


Introduction to Cruisecontrolrb – An RoR Integration Server

What is Cruisecontrolrb Cruisecontrol.rb is a simple and popular rails continuous integration server. Like continuous integration tools, its basic functionality is to build the source code of a project whenever a new commit is made to the main repository. Cruisecontrolrb setup Setting up cruisecontrol.rb for your app is very simple. You need to download it from https://github.com/thoughtworks/cruisecontrol.rb/downloads and setup onto your server as a simple rails application. After the cruisecontrol is setup, you need to add your project to it using the following console command:-
./cruise add  -u
You can alternatively add your project from UI as well by running the cuisecontrol application and by going to Add Project menu. Running Cruisecontrolrb After configuring your project, you can continue running it as rails app on port no 3000 or for a continuous monitoring you can start it on port 3333 by running the following command:-
./cruise start
Now whenever any of the developer checks in something to the main repository, it will monitor the activity and start building the project by fetching the code from that main repository. Configuring Cruisecontrolrb Cruisecontrolrb provides a lot of configuration options to the developers. Along with the inbuilt options there are a plenty of opensource plugins available to use with cruisecontrolrb. An example configuration to notify the developers regarding build failed and build fixed, you can mention configure their email addresses in the ~/.cruise/site_config file on your server as following(supposing sendmail/smtp is already configured on server) :-
<em>project.email_notifier.emails = ['abc@xyz.com', 'xyz@abc.com']
You can checkout more configuration options here. If you want to manually build the project, you can open UI on port 3333 and press the build now button. Already go to command line and type the following:-
./cruise build
Additional functionality and Plugins Cruisecontrolrb provides a plethora of flexibility to build additional functionality and plugins. There are several complex and basic callbacks exposed to developers to achieve the functionality required including but not limited to:- polling_source_control no_new_revisions_detected new_revisions_detected build_requested queued timed_out build_initiated configuration_modified build_started build_finished build_broken build_fixed build_loop_failed sleeping Apart from that, its very easy to write a plugin in cruisecontrol.rb. All you need to do is just to create a simple file with the following format:-
class SamplePlugin < BuilderPlugin
		  def build_finished(build)
		    //you custom code
		    //goes here
		  end
		end
		Project.plugin :sample_plugin
and save it in .cuise/builder_plugins folder. Enjoy the continuous  integration on your latest RoR app !!

Paypal Integration with RoR application – Securing the transaction

This post is in continuation with the Post Paypal Integration with Rails Application – Integrating IPN. It is important that we secure our paypal transactions with some sort of encryption so that evil hackers dont find it a cakewalk to hack across the various parameters being sent to the paypal server. This step is completely optional but very much neccessary for the secure payments on our website. Generating a Key Pair The first step in securing the payments is to create a key that only our app understands. For this purpose, Create a directory named as ‘certs’ to accommodate certificates. Now generate an openssl keypair and RSA certificate using the following commands:
mkdir certs
cd certs
openssl genrsa -out app_key.pem 1024
openssl req -new -key app_key.pem -x509 -days 365 -out app_cert.pem
Now you have two files in certs directory. Login Merchant’s Account -> Options -> Encrypted Payment Settings -> Add -> browse and select app_cert.pem file -> Add. After you are done, you will see a column ‘Cert ID’ ,copy and paste (in some text file) the text under this column, its your paypal certificate id. We will use if in further steps. Select the added certificate (using radio buttton) and click Download button. Move the downloaded file to our certs directory created above. Modifying the application logic Now we need to modify the application logic to encrypt the parameters and propogate the neccessary certificate information to paypal to be able to decrypt the parameters at its end. In paypal_url method of app/models/product.rb, add :
cert_id =&gt; AppConfig.cert_id, after :notify_url =&gt; notify_url, replace :business =&gt; YOUR_MERCHANT_EMAIL with :business =&gt; AppConfig.paypal_email and replace

1 1="+" 2="values.to_query" 3="[/php" language="https://www.sandbox.paypal.com/cgi-bin/webscr?"]
with
encrypt_for_paypal(values)
24.Add following code to encrypt the information being sent to the paypal:
PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem")

# openssl encryption.
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM),                                                         OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v|                                                                   "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)],                                                        signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"),                                                                                                                   OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
end
Set the following values in your configuration file.
development:
paypal_url: "https://www.sandbox.paypal.com/cgi-bin/webscr"
paypal_email:  YOUR_MERCHANT_EMAIL
cert_id: PAYPAL_CERT_ID

production:
paypal_url: "https://www.paypal.com/cgi-bin/webscr"
paypal_email:  YOUR_MERCHANT_EMAIL
cert_id: PAYPAL_CERT_ID
Note:PAYPAL_CERT_ID is the certificate id that is saved above. In app/views/products/index.html.erb, replace
product.paypal_url(products_url)
with
product.paypal_url(products_url, notification_products_url)
Login to merchant account -> Profile -> Website Payment Preferences -> Select ‘ON’ radio button under heading ‘Encrypted Website Payments’ -> Save. It will block non-encrypted websites to make payments. That’s it. You are now sending encrypted parameters to paypal. Troubleshooting: uninitialized constant AppConfig : Please use whatever protocol you use to load environment specific configuration settings.

Basic Paypal integration with RoR application

Paypal is now a widely accepted payment gateway by the developer community due to its global acceptability and ease of integration with all types of web applications. Here in this blog, we will learn to integrate Paypal Standard with Ruby on Rails(RoR) 3 application.

Sign up for Paypal sandbox account Paypal Sandbox lets you test your Paypal integration without actually charging your credit card or your paypal account. Sandbox is very handy tool to have while your application is in development mode. You can sign up for Paypal Sandbox here. Create Sandbox accounts We will need to create a seller and a buyer account on paypal sandbox for proper testing of payments. When you login to Paypal sandbox, you will see the following options to create accounts:
  • Create a preconfigured account and
  • Create an account manually.
You can use any of above mentioned options for creating accounts. You just need to create two accounts, one for seller and another for buyer. Set the application Scaffold the model. We assume that model is called as Product.
$rails generate scaffold product name: string unit_price: decimal
Migrate the changes to database
$ rake db:migrate
Set root for the application
root :to => 'products#index'
Start rails server ($ rails server) and add some products using link “New Product”. Add a link to buy now in your views(app/views/products/index.html.erb for this example), add following code for every products record We need to define the paypal_url for each product to be sold to communicate appropriate data to paypal. The function defines the various parameters for the paypal and returns them in the form of Query String.  More details about these query string parameters can be found on the paypal developer website. In app/models/product.rb

# This defines the paypal url for a given product sale
def paypal_url(return_url)
values = {
:business => YOUR_MERCHANT_EMAIL,
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => UNIQUE_INTEGER
}

values.merge!({
"amount_1" => unit_price,
"item_name_1" => name,
"item_number_1" => id,
"quantity_1" => '1'
})

# This is a paypal sandbox url and should be changed for production.
# Better define this url in the application configuration setting on environment
# basis.
"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query

end
Some notes about the parameters to be sent to Paypal:
  • : Invoice should be unique every time you make transaction.
  • : Cmd i.e. ‘_cart’ specifies that it’s for shopping cart purchases.
  • : upload = ‘1’ allows third party carts.
For making actual payments, you have to replace last line of above method to:
 "https://www.paypal.com/cgi-bin/webscr?" + values.to_query 
For actual payments you need merchant account on PayPal. 13.In app/controllers/products_controller.rb, add following code:
 flash[:notice] = "Your Transaction is #{params[:st]} for amount of $#{params[:amt]}. Thank You for shopping." if params[:st] 
That’s it!! Now start rails server and click on “Buy Now” link. It will land you to paypal’s payment page. Enter your buyer test account credentials and click login. Now you will see a page with some details, check them and click Pay Now. It will make transaction and will redirect you to return_url you sent from paypal_url method. Notes You will need to enable PAYMENT DATA TRANSFER in the merchant account. To do so, Login to merchant account -> Profile  -> Website Payment Preferences -> Find radio buttons under PAYMENT DATA TRANSFER and set it to ON. -> Click on Save. References
  1. Paypal Standard Integration Guide : https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_html_wp_standard_overview
  2. HTML Variables for Paypal Standard Integration: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables

Setting up single user rvm on ubuntu

RVM is a great tool for Ruby and Ruby on Rails(RoR) developers managing multiple RoR Projects with different ruby and gem configurations. Ubuntu has been growing as a choice for popular development and server Operating system. Lets hop onto our famous 1,2,3 howto format on how to install RVM on an ubuntu machine:
  1. Please ensure that you have curl installed on your system. If not, then its as simple as:
    sudo apt-get install curl
  2. Follow the single user installation instructions given on the rvm site to install rvm onto your system. You will find the instructions here.
  3. After you are done with the single user installation,  on your shell prompt, type
    type rvm | head -1
  4. If you get the following output, then rvm is correctly installed on your system. You can stop reading here and enjoy the magic of rvm on your ubuntu box .. :)
    rvm is a function
  5. If you dont get the above output, then we need to perform following additional tasks on your ubuntu box to configure and use rvm properly on your system.
  6. Go to your user’s home directory and open up .profile in your favorite editor such as vi/gedit and add the following lines to the end of file(This basically tells the shell to check if the rvm script exists at the default rvm script location($HOME/.rvm/scripts), and if it exists then executes all the commands in that rvm script files):
     [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function 
  7. The next step is to load the rvm for both interactive and non-interactive shells. This is the step which is missed by most of the beginners and major cause of lot of frustration around troubleshooting the rvm install. Find the following lines in ~/.bashrc file of yours:
  8. # if you see '[ -z "$PS1" ] && return' then you must change this line to:
    if [[ -n "$PS1" ]] ; then ... original content that was below the && return line ...
    fi # <= be sure to close the if. #EOF .bashrc Even if you use zsh you should still adjust the .bashrc as above.
    
  9. And that should be it. The command type rvm | head -l should work perfectly fine now.
Enjoy Multiple ruby and gem versions !!

Authorize.net and its Integration in Rails 3.x Application – Part 1

Authorize.Net is a payment gateway that enables merchants to accept credit card and electronic check payments via Web sites, retail stores, mail order/telephone order (MOTO) call centers and mobile devices. In other words, Authorize.Net enables the traditional credit card swipe machine you find in the physical retail world on the web.

Recently, we had an implementation where we had to integrate Authorize.net with a Rails 3.x application. The integration is a cake walk and is very easy for even the novice programmers to follow:

1. The first thing we need is a developer account on Authorize.net. Sign up for test account to get API Login ID and Transaction Key. You can sign up from here. Enter you details and select “Card Not Present” as Account Type. Click submit.

2. After successful sign up, you will get a welcome email from authorize.net developer center which contains some test credit cards numbers.

3. Now simply log in to the Merchant Interface and click “Account.” Then click “API Login ID and Transaction Key.” Your API Login ID will be displayed. For security reasons, you cannot view your Transaction Key. Instead, you must generate a new one. To do this you will need the Secret Answer to the system-generated Secret Question, which is “Simon”.

4. There are 3 major ways to implement authorize.net in your application:

  • Server Integration Method (SIM)
  • Direct Post Method (DPM) and
  • Advanced Integration Method (AIM)

In this particular blog post, I am going to discuss Server Integration Method (SIM). There are two main features of this method:

  • Provides a customizable, secure hosted payment form.
  • Authorize.Net handles all the steps in the secure transaction process.
  1. We will use authorize-net gem for this particular case. To integrate SIM in your rails application, open the file “Gemfile” in the root directory of your new rails application and add the following line to the end of the file:
gem 'authorize-net'

   and run “bundle install” command from console.

  1. Run the following command it will scaffold everything which we need for integration.
$ rails generate authorize_net:sim payments YOUR_API_LOGIN_ID YOUR_TRANSACTION_KEY YOUR_API_LOGIN_ID
  1. Open config/routes.rb and add the route to the method to claim the payments:
root :to => 'payments#payment'
  1. Now your application is ready to run. Start the server using following command:
$ rails server

You will see a page displaying total amount to be paid and a payment button. If you are facing some errors while starting server, refer to Troubleshoot section of the blog.

  1. Terminate the server and open app/views/payments/payment.erb. It will looks like:
</pre>
<%= form_for :sim_transaction, :url => AuthorizeNet::SIM::Transaction::Gateway::TEST do |f| %>
 <%= sim_fields(@sim_transaction) %>
 <%= label_tag 'x_amount', "Total: #{number_to_currency(@amount)}" %>
 <br />
 <%= f.submit 'Purchase'%>
<% end %>

  1. Add following code after the label_tag:
</pre>
<%= hidden_field_tag("x_invoice_num", UNIQUE_INVOICE_NUMBER, {:id => "x_invoice_num"}) %>
<%= hidden_field_tag("x_cust_id", CUSTOMER_ID, {:id => "x_cust_id"}) %>
<%= hidden_field_tag("x_email", EMAIL_ID, {:id => "x_email"}) %>

In above code you have to replace UNIQUE_INVOICE_NUMBER , CUSTOMER_ID, EMAIL_ID with some values or variables. Invoice number should be unique for every payment transaction.

  1. Open app/views/payments/thank_you.erb and add a link to root of your application.
</pre>
<%= link_to "Home", root_path %>
<pre>

5. Start your rails server and open the application on browser. Click the “Purchase” button and complete the payment form that appears on the hosted payment page.

6. Select “Visa” and enter any test credit card, any expiration date (MMYY) in the future (such as “1120”), and hit “Submit”.

7. That’s it!! The payment is completed and the user will be redirected to thank you page.

Please feel free to drop a comment in case you have any queries.

Troubleshooting:

  • uninitialized constant RAILS_ROOT: Open config/initializers/authorize_net.rb and replace RAILS_ROOT with Rails.root
  • uninitialized constant RAILS_ENV: Open config/initializers/authorize_net.rb and replace RAILS_ENV with Rails.env

Source Code : The source code for this blog can be found at github.


Installing redmine on a shared host(Bluehost/Dreamhost/Apthost/Hostgator etc)

Redmine is a popular open source tool built on top of RoR. Recently, we@enbake got a task to install Redmine on a shared host.  We faced several problems during the process to which we thought that documentation were necessary. I will take you through a step by step guide to install redmine on a shared host. The host happened to be apthost for our case but i guess that the same would apply for bluehost, dreamhost, apthost and other shared hosts.
  1. Ensure that you have the ssh access to your server. If you dont have currently, then please apply for ssh access to your host.
  2. Once you have ssh access. Login into server via ssh.
  3. Please check the ruby and the rails version on your host and download the appropriate redmine source code from http://www.redmine.org/projects/redmine/wiki/Download
  4. Extract redmine to the target folder. For the ease of this guide, we assume that redmine was extracted to ~/redmine.
  5. Create a database using mysql on your server(most probably using cpanel) and add appropriate database settings to the rails config/database.yml.
  6. Install the gems required by redmine using rake gems:install. The command will install gems onto your user home directory and you might need to add the gem path to your .bash_profile.
  7. If your .bash_profile does not contain the following directives, please add them to it:
  8. export GEM_PATH=/usr/lib/ruby/gems/1.8:~/ruby/gems export GEM_HOME=~/ruby/gems (here ~/ruby/gems is the path where local gems are usually installed)
  9. Redmine stores session data in cookies by default, which requires a secret to be generated. So we need to generate session store secret. Under the application main directory run: rake generate_session_store
  10. Create the database structure by running the redmine migrations: RAILS_ENV=production rake db:migrate
  11. Migrations will create all the tables and an administrator account with admin/admin as username/password.
  12. The user who runs Redmine must have write permission on the following subdirectories: files, log, tmp & public/plugin_assets:- chown -R user:group files log tmp public/plugin_assets chmod -R 755 files log tmp public/plugin_assets
  13. Redmine comes with a prebuilt dispatcher and .htaccess files. Rename the .example dispatcher files to their respective extensions. Similarly rename the example .htaccess to .htaccess
  14. Test the installation by running the WEBrick web server. Under the main application directory run: ruby script/server -e production
  15. If there is no error in step 14, then the redmine is all set and now you should move ahead to configure apache to serve the redmine. Otherwise, please move back and check the errors.
  16. We will install redmine on a subdomain in this guide since most of the shared hosts support subdomaining.
  17. Create a subdomain using cpanel’s subdomain management option. Give it some path in the apache directory. Normally ~/public_html. Lets say the path is ~/public_html/redmine and the subdomain is redmine.tld.com for the purpose of this guide.
  18. Now move to shell again and make a symbolic link in ~/public_html/redmine to your redmine install’s public directory (~/redmine) in this case. This command will create a symbolic link : ln -s ~/redmine/public ~/public_html/redmine
  19. Add the local gem path in your config/environment.rb file ,  ENV[‘GEM_PATH’]=’/home/username/ruby/gems:/usr/lib/ruby/gems/1.8′
  20. Run the application by entering your application’s url in browser and your shiny new redmine install should be there.
Enjoy Managing your projects !!

uninitialized constant Delayed::Job in rails 2

If you have installed delayed job gem/plugin to manage background job and are facing the problem
uninitialized constant Delayed::Job
Then you need to add the following to config/initializers/delayed_job.rb
Delayed::Worker.backend = :active_record
This will remove the error and you will now be able to work with delayed job in your rails application. Enjoy the sweetness of backgrounded jobs.  

Using Amazon SES for email delivery in Rails 3

Recently, Amazon added a new product to their cloud services kitty called as Amazon SES(Amazon Simple Email Service). The service can be used for bulk and transactional emails by developers and businesses alike. So as you might have guessed by now, the service competes head on with Postmark, Sendgrid, socketlabs etc. The simple reason for scrapping the said services and going ahead with Amazon SES is the price, thats it !! Now, lets dive deep into how to get Amazon SES running with a simple web application(We will be using rails3 as an example client application in this writeup): Setting up Amazon SES for delivering emails 1. Apply for the activation of SES in your amazon AWS account. If you are an existing AWS user, you will already be getting Amazon marketing promos to activate SES. Or you can sign up for ses here. 2. By default Amazon SES will be activated in a sandbox mode. This means that all the email addresses that you will be sending mails to, will need to be verified otherwise the email wont be delivered. Also, with verified email addresses, you can send up to 200 messages per day, at a maximum rate of 1 message per second 3. To get your email addresses verified, download Amazon SES scripts 4. To run the SES verification script, Perl must be installed on your system with the dependent modules. 5. Run the following command: ses-verify-email-address.pl -k creds.txt -v Amazon will send an email at the specified address. Please click the link in that email and you are done with the verification process. You are now done with verifying this email address. Please note that creds.txt here contains the AWS credentials. A sample creds.txt file looks like: AWSAccessKeyId= your_access_key AWSSecretKey= your_secret_key 6. After testing your emails in the sandbox, you can click here to Request for Production Access to Simple Email Service. They say it may take up to 24 hours, but my access request was granted in about 30 minutes – now I can send to any address! This was all about setting up Amazon SES. Now lets move to integrating the setup with a Rails 3 application. Configuring a Rails 3 application to send mails through Amazon SES: There are already a number of open source gems/plugins available to configure action mailer to send email thro Amazon SES but we decided to go ahead with drewblas/aws-ses (the aws-ses gem) for a simple reason that it works painlessly. Now: 1. Add ses to the gem file
gem "aws-ses"
2. Extend ActionMailer in config/initializers/your_config_file.rb, where config_file.rb is the name of the file which contains initialization routines for ses gem:
ActionMailer::Base.add_delivery_method :ses, AWS::SES::Base,
  :access_key_id     => ENV['AMAZON_ACCESS_KEY'],
  :secret_access_key => ENV['AMAZON_SECRET_KEY']
3. Configure action mailer to send thro ses. In config/environments/*.rb
config.action_mailer.delivery_method = :ses
Thats it !! You are now ready to send mails from rails app thro Amazon SES. Happy Mailing !!