Monthly Archives: October 2013

URL Shortening on Rails 3 with Bit.ly

For integrating with twitter you need to shorten url. I have used this gem

First add gem to your gemfile

gem bitly

and run

bundle install

Now add this to your controller

require ‘bitly’

philnash’s gem has support for the bit.ly version 2 and version 3 api. I have use version 3.

Create a new file config\initializers\bitly.rb and write this.

Bitly.configure do |config|
  config.api_version = 3
  config.login = "##############"
  config.api_key = "##################################"
end

That’s it from installation.

Here is code from controller. This is the example from the gem documentation

u = bitly.shorten('http://www.google.com') #=> Bitly::Url

u.long_url #=> "http://www.google.com"
u.short_url #=> "http://bit.ly/Ywd1"
u.bitly_url #=> "http://bit.ly/Ywd1"
u.jmp_url #=> "http://j.mp/Ywd1"
u.user_hash #=> "Ywd1"
u.hash #=> "2V6CFi"
u.info #=> a ruby hash of the JSON returned from the API
u.stats #=> a ruby hash of the JSON returned from the API

Based on this your result is expected. if you want the short url try

bitly.shorten("http://domain.com/articles/#{id}").short_url

That’s it. Happy coding 🙂

Create dynamic sitemap on ruby on rails

What is sitemap:

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

It’s basically a XML file describing all URLs in your page:

The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics.

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

   <url>

      <loc>http://www.example.com/</loc>

      <lastmod>2005-01-01</lastmod>

      <changefreq>monthly</changefreq>

      <priority>0.8</priority>

   </url>

   <url>

      <loc>http://www.example.com/catalog?item=12&amp;desc=vacation_hawaii</loc>

      <changefreq>weekly</changefreq>

   </url>

   <url>

      <loc>http://www.example.com/catalog?item=73&amp;desc=vacation_new_zealand</loc>

      <lastmod>2004-12-23</lastmod>

      <changefreq>weekly</changefreq>

   </url>

   <url>

      <loc>http://www.example.com/catalog?item=74&amp;desc=vacation_newfoundland</loc>

      <lastmod>2004-12-23T18:00:15+00:00</lastmod>

      <priority>0.3</priority>

   </url>

   <url>

      <loc>http://www.example.com/catalog?item=83&amp;desc=vacation_usa</loc>

      <lastmod>2004-11-23</lastmod>

   </url>

</urlset>

 

Creating your dynamic sitemap with Ruby on Rails:
First write this on your routes file.

map.sitemap "/sitemap.:format",
     :controller => "home",
     :action => "sitemap",
     :conditions => { :method => :get }

So sitemap URL will be http://www.mysite.com/sitemap.xml
Now on controller write some method to fetch data.

@posts = Post.all
@categories = Category.all

Now the logic is done and you have to create view for your sitemap to show that sitemap when some request riches http://www.mysite.com/sitemap.xml.

We need to build a XML containing the 3 main nodes to make it a sitemap:

loc – The URL of your page
priority – The priority of the indexing page process between 0 and 1
lasmod – Date of the last modification
changefreq- How frequently the page is likely to change. This value provides general information to search engines and may not correlate exactly to how often they crawl the page. Valid values are

  • always
  • hourly
  • daily
  • weekly
  • monthly
  • yearly
  • never

First node is mandatory, the others are optional. Using the XML builder, create the file sitemap.xml.builder to our sitemap and put the next lines:


base_url = "http://#{request.host_with_port}"
xml.instruct! :xml, :version=>'1.0'

xml.tag! 'urlset', "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do

  xml.url do
    xml.loc "#{base_url}"
    xml.changefreq "monthly"
    xml.priority 1.0
  end

  xml.url do
    xml.loc "#{base_url}/FAQ"
    xml.lastmod Time.now.to_date
    xml.changefreq "monthly"
    xml.priority 1.0
  end

  xml.url do
    xml.loc "#{base_url}/contact-us"
    xml.lastmod Time.now.to_date
    xml.changefreq "monthly"
    xml.priority 1.0
  end

  xml.url do
    xml.loc "#{base_url}/about"
    xml.lastmod Time.now.to_date
    xml.changefreq "monthly"
    xml.priority 1.0
  end

  @categories.each do |category|
    xml.url do
      xml.loc category_url(category)
      xml.priority 0.9
    end
  end

  @posts.each do |post|
    xml.url do
      xml.loc post_url(post)
      xml.lastmod post.updated_at.to_date
      xml.changefreq "always"
      xml.priority 0.9
    end
  end

  @categories.each do |category|
    xml.url do
      xml.loc category_url(category)
      xml.lastmod post.updated_at.to_date
      xml.changefreq "always"
      xml.priority 0.9
    end
  end

end

That’s it. Happy coding 🙂

Prevent browser page caching

One of my rails application shows problem about browser caching. After destroying all login session page redirect back me to my home page. But when I click my browser back button I still see the login pages.

Here is few solution for that.

Clear Cache/No-Cache :

// Code disables caching by browser. Hence the back browser button
// grayed out and could not causes the Page_Load event to fire
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore(); </pre><p><strong> Use Meta Tag for No-Cache: </strong></p><pre>&lt;meta Http-Equiv="Cache-Control" Content="no-cache"&gt;
&lt;meta Http-Equiv="Pragma" Content="no-cache"&gt;
&lt;meta Http-Equiv="Expires" Content="0"&gt;

Clears Browser History and Redirects URL:

//clears browser history and redirects url
&lt;SCRIPT LANGUAGE="javascript"&gt;
{
     var Backlen=history.length;
     history.go(-Backlen);
     window.location.href=page url
}
&lt;/SCRIPT&gt;

Rails :

Write this code on application controller.

before_filter :set_cache_buster

  def set_cache_buster
    response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
  end