Skip to main content

Posts

Showing posts from January, 2014

Get the Current url in ruby on rails

request.refererrequest.fullpathrequest.fullpath.split("?")[0]request.referer or request.env['HTTP_REFERER'] your controller to get the referer url. 

--------------------
request.original_url
request.url
request.host_with_port
<link rel="canonical" href="<%= request.url %>" />
<%=request.path%>
How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.
request.env['REQUEST_URI']

 For Rails 3.2 or Rails 4 you should use request.original_url to get the current URL. More detail.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address

Adding Column to rails 2 and rails3

##add cloumn to rails

rails g  migration AddStatusToUsers
class AddStatusToUser < ActiveRecord::Migration
  def change
          #add_column :table_name, :column_name, :type, default: "Your value"
        add_cloumn :users,:status,:string
  end
end
###############change column names to rails
rails g migration ChangeNameToUsers
class RenameStatusToUser < ActiveRecord::Migration
  def change
      #rename_column :table_name, :old_column1, :new_column1
    rename_column :users,:name,:full_name
  end
end
  (or)
class RenameStatusToUser < ActiveRecord::Migration
  def change
    change_table :table_name do |t|
      t.rename :old_column1, :new_column1
      t.rename :old_column2, :new_column2
    end
end

########ROR migration change a column type from Date to DateTime
rails g migration change_date_format_in_my_table
class ChangeFormatInUser< ActiveRecord::Migration
  def change
    #change_column :my_table, :my_column, :my_new_type
    change_column :users
  end
end


##for rails2 adding column
ruby …

Rake Task In Ruby On Rails

namespace :update_user_staus do
  desc "updating user status"
  task :update => :environment do (or)###for create 'task :create => :environment'
    User.all.each do |b|
    b.status = "active"
    b.save
  end
 end
end

######running command

rake  update_user_staus:update

Generate Random string in Ruby On Rails

##method 1
def random_password(size = 6)
chars = (('a'..'z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l 0)
(1..size).collect{|a| chars[rand(chars.size)] }.join
end
 puts random_password.inspect

##method 2
 def newpass(len=6)
  chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  newpass = ""
  upto(len) { |i| newpass << chars[rand(chars.size-1)] }
 return newpass
end
p newpass.inspect

##method 3
def generate_string(a)
new_code = random_string(6)
end
p  new_code.inspect

###correct_method
##method 4
def random_string(length = 6)
chars = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a
(1..length).map {chars[rand(chars.length)]}.join
end
p random_string.inspect

##method 5
def random_string(length = 6)
rand(36**length).to_s(36)
end
 p random_string.inspect

##method 6
def random_string
 o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a…

Ruby Basic Concepts overview

Ruby was written to make the programmer’s job easy and not care if the computer’s job is hard. In this brief introduction we’ll look at the key language features you need to get started.

    Instructions and Interpreters
    Variables
    Methods
    Strings
    Numbers
    Symbols
    Collections
        Arrays
        Hashes
    Conditionals
        Conditional Decisions
        Conditional Looping
    Nil & Nothingness

If you haven’t already set up Ruby, visit the environment setup page for instructions.

This tutorial is open source. If you notice errors, typos, or have questions/suggestions, please submit them to the project on GitHub.
Ruby History

Ruby is thought of by many as a "new" programming language, but it actually was released in 1994 by a developer known as Matz. Matz is a self-described "language geek" and was a particularly big fan of Perl. His idea for Ruby was to create a language that was flexible and powerful like Perl, but more expressive …

URL Shortening on Rails 3 with Bitly

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…

Create dynamic sitemap on ruby on rails

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&g…

Parse Feeds/Blogs From External Sites To Your Rails App

Step 1

Add gem in your gem file

gem 'feedzirra'

Run the bundle install

Step 2

Go to your required controller and add the following at top.

require 'feedzirra'

Step 3

In your controller create a method and add the following block to fetch feeds from external sites


feed = Feedzirra::Feed.fetch_and_parse("http://feeds.feedburner.com/TechCrunch/gaming")
@entry = feed.entries

It will fetch the list of feeds from the blog site.

Step 4

Add the following block in your view page


<%@entry.each do |feed|%>
 <%= link_to "#{feed.title.sanitize}", "#{feed.url}",:target => "_blank" %>
 <%=feed.author%>  
 <%=feed.published%>
 <%=feed.categories %>
<%end%>

Twitter and Linkedin Integration Using Devise and Omniauth In Rails App.

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-twitter'

Run the “bundle install” command to install the gem.

Step:2
You need two more columns to store provider type and userid given from twitter

rails g migration AddProviderToUsers provider:string uid:string

Runt rake db:migrate to insert the columns in users table.

Step:3
Go the user model “user.rb” and add the following line

devise : omniauthable

Step:4
First of all you need to create an app in twitter to get “Consumer key” and “Consumer Secret key”

https://dev.twitter.com/apps

Create an app and get the App id and secret key.

Step:5
Now you need to declare the provider name and app id and key.Go to the file config/initializers/devise.rb and the following line

require 'omniauth-twitter'
config.omniauth :twitter, "APP_ID", "APP_SECRET"

Step:6
Go to your layout file and the following block


<% if user_signed_in? %>
Signed in as <%= current_user.name %…

Test-Driven Development (TDD) with Rails 3 and rspec

Let’s create out edit test.

To add edit test  you have to modify your spec file.

require 'spec_helper'

describe "Tasks" do
  before do
    @task = Task.create :task => 'go to bed'
  end

  describe "GET /tasks" do

    it "display some tasks" do
      visit tasks_path
      page.should have_content "go to bed"
    end

    it "creates a new page" do
      visit tasks_path
      fill_in 'Task', :with => 'go to work'
      click_button "Create Task"

      current_path.should == tasks_path
      page.should have_content 'go to work'

      save_and_open_page
    end

  end

  describe "PUT /tasks" do
    it "edits a task" do
      visit tasks_path
      click_link 'Edit'

      current_path.should == edit_task_path(@task)
      #save_and_open_page

      #page.should have_content 'go to bed'
      find_field('Task').value.should == 'go to bed'
      fill_in 'Task&…

Access Rails Development Server From A Different Computer Sometime you need to access your rails app from a different computer.

To access your rails app from different computer, you need to run rails app with IP.
While starting the webrick server specify the IP on which your rails application will run (192.168.1.x in your case) using -b option, it binds Rails to the specified IP.
1 rails server -b 192.168.1.x -p 3000

Import CSV File Into The Database In Rails Application.

Step:1
Add the following line in application.rb file

require 'csv'

Restart the server.

Step:2
Add the block in your view page for users to upload CSV file.

<%= form_tag home_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import CSV" %>
<% end %>

Step:3
Add the block in your controller

def import
   Users.import(params[:file])
  end

Step:4
Go to user model and write the following code block

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Users.create! row.to_hash
  end
end

Google Integration Using Devise and Omniauth In Rails App.

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-google-oauth2'

Run the “bundle install” command to install the gem.

Step:2
You need two more columns to store provider type and userid given from google

rails g migration AddProviderToUsers provider:string uid:string

Runt rake db:migrate to insert the columns in users table.

Step:3
Go the user model “user.rb” and add the following line

devise : omniauthable

Step:4
First of all you need to create an app in google to get “Client key” and “Client Secret key”

https://code.google.com/apis/console/

Create an app and get the Client id and secret key.

Step:5
Now you need to declare the provider name and client id and key.Go to the file config/initializers/devise.rb and the following line

require 'omniauth-google-oauth2'
config.omniauth :google_oauth2, "APP_ID", "APP_SECRET", { access_type: "offline", approval_prompt: "" }

Step:6
Go to your layout fil…

Facebook Connect Integration Using Devise and OmniAuth In Rails App.

Step:1
Add the gems in your gem file

gem ‘devise’
gem 'omniauth'
gem 'omniauth-facebook'

Run the “bundle install” command to install the gem.

Step:2
Define your root url like below

root :to => “home#index”

Step:3
Now you need to run the generator command

rails generate devise:install

This generator will install all Devise configurations.Take a look at them.

Step:4
After done with the above options,you are ready to add Devise to any of your models using the generator:

rails generate devise User

This generator creates a few interesting things: a model file, a migration and a devise_for route.

Step:5
Go the user model “user.rb” and add the following line

devise : omniauthable

Step:6
Run the migrate command to insert the User table in your database.

rake db:migrate

It’ll insert the Users table with some columns.

Step:6
You need two more columns to store provider type and userid given from facebook

rails g migration AddProviderToUsers provider:string uid:string

Runt rake db:migrate to insert the…

Ruby On Rails Interview Questions for Freshers...

1. Why Ruby on Rails?
Ans: There are lot of advantages of using ruby on rails
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept
6. Rest Support
7. Rack support
8. Action Mailer
9. Rpc support
10. Rexml Support
11. etc..


2. Explain about the programming language ruby?
Ruby is the brain child of a Japanese programmer Matz. He created Ruby. It is a cross platform object oriented language. It helps you in knowing what your code does in your application. With legacy code it gives you the power of administration and organization tasks. Being open source, it did go into great lengths of development.

3. Explain about ruby names?
Classes, variables, methods, constants and modules can be referred by ruby names. When you want to distinguish between various names you can specify that by the first character of the name. Some of the names are used as reserve words which should not be used for any other purpose. A name can be lowercase letter, upper c…