Add Google Custom Search to your Rails Application (Business Edition)
Here are the steps to set up a Google CSE for your rails application. In order to use the xml api, first of all you need to have a business account. You can get the xml query format url or more precisely the cx parameter (unique ID of the CSE) from the control panel.
Setup:
Identify your resource to be searched with the help of url patterns. For ex, if the application is RESTful, it is easy to index something like http://someshop.com/products. Configure your CSE for the above url pattern so that http://someshop.com/products/1, http://someshop.com/products/2.. etc get indexed by the search engine.
Code:
The GoogleSearch class sends a GET request to fetch the results xml, which is parsed using the Hpricot parser.
Output:
Now you could get the urls of search results as an array. Likewise, you can fetch other parameters from resultant xml by referring the this doc..
Remote file storage using File Column plugin
Many times I came across a need to fetch remote data (video files/images) and store them on file system. Searching for a way, I came up with this approach.
The example is about a Video class with a video_file ‘file_column’. To fetch and store a remote file instead of getting it as a post parameter, we need to do some code workaround. The example below demonstrates one approach.
Usage:
My model looks as simple as this:
JS based easy Field Validations in Rails
Most of you will disagree with this post to use Javascript based form validations in Rails. However this is an attempt to simplify integration of DEXAGOGO - Really easy field validations in Rails. This is one of the most structured and easy validation technique written by Andrew Tetlaw and team. (Demo)
To use it in Rails, copy simple_validation.rb in application lib directory and add following lines to config/environment.rb file.
Download and Import validation.js along with prototype.js in layout from here.
Two methods are introduced to render forms.
- validated_form_for
- validated_remote_form_for
Usage:
:class attribute refers to validation rule (or combination of rules) and :title attribute is the validation message. Details of all rules are available at http://tetlaw.id.au/view/javascript/really-easy-field-validation
File Upload: Validating Extensions
I was searching for a way to validate a file against an allowed set of extensions before uploading. My application uses file_column plugin to store video files and I am using mongrel_upload_progress to track the upload. The maximum file size allowed is 50Mb so there was a need to have validation at both client as well as server side.
Model Validation
Client Side javascript validation
mongrel_upload_progress plugin uses following code to submit the form in a hidden iframe. Modify submitUploadForm method as shown:
The advantages of this approach are:
File is validated at both sides to avoid unnecessary uploading of file before model validation. Good for big files.
In case JS is disabled, the file is still validated.
Ajax Tree Plugin
Introduction
This is a helper plugin to generate ajax based tree structure (two level). It can be used for two models having n:m or 1:n relationships. A leaf from any branch can be dragged and dropped in another branch. A scaffolding arrangement is also done to create a new branch, add leaf etc.

For example:
Installation:
Here we take the previous example of Category and Article models. Generate the ajax controller for the two models.
Usage
Example
Copy static files
Copy add.png, delete.png from /vendor/plugins/ajax_tree/ directory to /public/images directory.
Copy ajax_tree.css file from /vendor/plugins/ajax_tree/ directory to /public/stylesheets/ directory.
Include css in your application layout
Call the helpers
Specify model names for branch model and leaf model in /views/home/_show_ajax_tree.rhtml partial.
Then, call this partial in any rhtml, where you want to display the ajax tree. In this case, we have done it in /views/home/index.rhtml
home_controller.rb (Generated automatically)
index.rhtml
Contributions:
This project is hosted at http://code.google.com/p/ajax-tree/. Please leave your feedback.
Flash Movie embed code (RubyOnRails)
Last week I was working on a code to make my video files embedding (flv) available for external webpages. There are many ways to implement this and I have documented a simple way to achieve it.
I am using a Video model with file_column plugin to store the flv file. The path of stored flv files is /public/video/file_path/[id]/[filename.flv] in my application. I am using ffmpeg to convert files to flv format but I am not including this module here.
Here is the controller to access the video files from server filesystem.
To make this url http://server.com/video/index/[id] to something DRY like http://server.com/v/[id], add this mapping to your routes.rb file.
map.connect ‘v/:id’, :controller => ‘video’, :action => ’show’
The Video model with embed_code method looks as follows:
Finally, @video.embed_code gives the code to embed a video as a swf object in external html page.
yaml_form_builder
This plugin provides a simple way to generate dynamic forms in view. The forms are configured with the help of a yaml configuration file.
1) Installation
script/plugin install http://yaml-formbuilder.googlecode.com/svn/trunk/yaml_form_builder/
2) Configuration
The example below demonstrates a form generated for the following schema.
3) Configuration
Create a file named formconfig.yml in /config directory.
4) Controller
Fetch records in the controller.
5) Finally the helper in View
(views/form/index.rhtml)
The url /form/index shows a form, generated dynamically with the help of above yml configuration file.
Client for Yahoo! Search webservices in RubyOnRails
Here is a client for Yahoo search api using the simplest web service architecture REST (Representational State Transfer).
Working demo: http://demo.anup.info/search
The client application works as:
To begin with, get an application ID from http://developer.yahoo.com.
Controller: search_controller.rb
View: index.rhtml
Partial view: _results.rhtml
Partial View: _error.rhtml
Prototype Window Login Form with Ajax/RJS
Here is a simple tutorial to demonstrate the use of prototype Window login form with RubyOnRails and Ajax. The idea behind this is to override Ok event of Dialog.confirm() form and send Ajax request to controller. The demo application makes use of RJS for Ajax callbacks.
To begin with, download prototype windows library, copy javascripts in your public/javascripts folder and themes to stylesheets folder.
Include the javascripts and stylesheets in layout header.Look at our application.rhtml layout for complete details.
Dynamic Subdomains with RubyOnRails
Following is a step by step guide to configure an application for dynamic subdomains. We are trying to set up wildcard subdomain feature similar to the one done by blogspot.com and wordpress.com.
Step 1
In advanced DNS settings of your domain, add an A record as follows
*.domain.com IN A ***.***.***.*** (server IP address)
Step 2
Modify http.conf to set up a serveralias *.domain.com for http://www.domain.com/.
Make sure you have access, or ask your service provider to do this.
Step 3
Add a wildcard entry for your domain in the Zone file for http://www.domain.com/, so that nonexistant subdomains are resolved to same public_html folder.
Now to check this, keep an index.html file in the public_html folder.
Try browsing http://www.domain.com/ and http://anything.domain.com/ . Both should resolve to the same index.html file. If this succeeds, your dynamic subdomains are set up.
To catch the subdomain in RubyOnRails modify application.rb as follows,
class ApplicationController < ActionController::Base before_filter :get_subdomain # # Other content goes here # private def get_subdomain @subdomain = request.subdomain.first @subdomain = 'www' if @subdomain.nil? end end
Now you have a subdomain catched by your application controller which can be used in all controllers.
For example, MyController makes use of @subdomain and decides what action to take. (it is a simple redirect action in this case)
class MyController < ApplicationController def index if subdomain == 'anup' redirect_to_url 'http://anup.info' else if subdomain == 'planet' redirect_to_url 'http://planetrubyonrails.com' else redirect_to_url 'http://yourdefaulturl.com' end end end
