Archive for the ‘rails’ Category

9 Things You Should Know About Ruby on Rails

There are many programming languages, different frameworks, and uncountable developers. But Ruby on Rails has become one of the most popular languages among the developers. Though most of the people start their programming career with languages like Java, C++, PHP, etc., Ruby on Rails is what startups and some full-fledged companies use while developing websites. Image result for ruby on rails The first question that crosses everyone’s mind after hearing ‘Ruby on Rails’ is ‘What is Ruby on Rails?’. In this article, we are going to discuss some important things about ‘Ruby on Rails’. Let us start-

1. What is Ruby on Rails? Is it one thing or Ruby and Rails are two different things?

To be specific, Ruby is a programming language, whereas Rails is a web application framework designed to work with Ruby. Ruby is simple to learn and is super fun. It is easier than other programming languages. But the only problem with Ruby was that it was not designed for use on the web until Rails came. Rails are the most popular framework for Ruby basically make it possible to write a Ruby application and have it be a website.

2. Is ‘Rails’ good for the beginners?

Before moving to ‘Rails’, the first thing you need to learn is Ruby. The reason behind ‘Rails’ being good for beginners is because Ruby is simple to learn. Ruby is easier because the language is super flexible and not always case sensitive. And Rails is fun for beginners because it is robust and it does so much of the hard work for you. The developers do not have to bang their heads to find a minute mistake in the whole code. Basically, the first you have to learn Ruby and then you will be able to learn Rails.

3. How is Rails developer different from Ruby programmer?

As mentioned above, you have to learn Ruby first because Rails is a framework. Technically, a good developer can easily on Ruby web apps using other web frameworks like Sinatra. But a developer would not be hired just to write Ruby, So, it is important for a Ruby developer to learn Rails for future.

4. How good should a developer be to get hired as Ruby on Rails professional? What makes Rails so special?

To be honest, it takes a lot of time to become a Ruby on Rails expert. Basically, you should be comfortable in working on Ruby. You cannot dive into Rails without learning Ruby, but it is important to learn Rails afterwards. It is just like learning to ride a bicycle before learning to ride a bike. Specifically, you need to know about all the basics including data types, object orientation, debugging, etc. And the thing that makes Rails so special is because of its rapid prototyping. You can develop a Rails app with few hours. There are few frameworks that could make it possible.

5. What could be built with it?

Well, the answer is you can build any web application with Rails. Some of the most popular website built on Ruby on Rails are Shopify, Airbnb, Bloomberg, SoundCloud, etc.

6. Is possible to build mobile apps with it?

This is a bit complicated. It is not possible to literally build a mobile app in Rails. But you can build a web application in Rails, and use it as the backend for a mobile app. There are other options like RubyMotion which makes it easy to build native iOS and Android apps using Ruby. Talking in a straightforward manner, you cannot literally use Rails in developing mobile apps, but it could be an important part of the project.

7. Shouldn’t I learn JavaScript instead?

Well, if you are asking instead, then the answer is no. And if you ask also, then the answer is yes. The reality is a Ruby on Rails developer to need to learn JavaScript one time or another. It is not a prerequisite skill but it will help in future for further progress. And if you are thinking about which one you should be learning first, then the answer is Ruby is easier to learn than JavaScript. JavaScript is the first preference of students, but in the end, you have to learn both.

8. How long would it take to learn?

A few months of dedicated study can make you comfortable with Ruby on Rails. But if you want to be a master, you have to give at least 10,000 hours. Your level of familiarity with different programming languages would have an impact on you being comfortable with Ruby on Rails.
Also Read:Java vs JavaScript- All You Should Know

9. How to get started with this?

If you are already familiar with programming languages, then it would be easy for you to learn Ruby on Rails. But if you don’t know even a single thing about coding, then first you need to learn HTML & CSS. And then you need to learn Ruby, Git & command line.
The most important thing you need to do while learning something is having a project by your side. It would help you to learn, and find out your weak spots. These are the most common questions that come to everyone’s mind. So, if you have any question, just comment below and we will try to answer it!

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.