Skip to main content

Posts

Showing posts from January, 2014

Get the Current url in ruby on rails

request . referer   request . fullpath request . 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 DateTi...

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'),(...

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" p...

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 #=> ...

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>     ...

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? %> Si...

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 ...

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: "" ...

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...

Checking Empty or nil in ruby on rails

Checking for array is empty in ruby @user = User.where(:name => "chinna").all <%unless @user.empty?%> <%@user.each do |u| %> <%=u.email%> <%=u.dob%> <%end%> Ruby on rails undefined method `name' for nil:NilClass <%@user.name unless @user.name.nil? %> ##Cheking for params[:name] is present or not? @user = User.where(:id => params[:id]).first if params[:name].present?  @user.update_attributes(:name => params[:name]) end

Pagination,Checking admin role and case statements in Ruby on Rails

a = User.where(:email => "chinna@yopmail.com").first a.update_attributes(:age => 23) (or) a.age = 23 a.save Collect the total user_ids  user_ids = User.collect{|x|x.id}  ######user_ids = [1,2,3,4,5,6] like that only you will get  user_ids.each do |u|  <%user = User.where(:id => u).first%> <%=user.email%> <%=user.name%>  <%end%>  ###pagination in rails with will_paginate gem 1)Controller  @users= User.paginate(::page => params[:users], :per_page => 10) 2)in views ####<%= will_paginate @users, :param_name => 'users' %> ##display records in descending order @user = User.order("created_at desc").limit(10) ###some of methods in model   def check_admin?     self.role == "admin"   end  ####In views <%if @user.check_admin? %> <%=link_to "Users",users_path %>  <%end%>  ###case statements in ruby on rails  def is_check_user(user)    case user...

TWITTER FOLLWERS AND FRIENDS IN RAILS using omniauth-twitter gem..

## Gem file add this one gem 'omniauth-twitter' ##config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do   provider :twitter, "CONSUMER_KEY", "CONSUMER_SECRET" end ####Getting the twitter omniauth data twitter_omniauth = request.env['omniauth.auth'] {   :provider => "twitter",   :uid => "123456",   :info => {     :nickname => "chinna",     :name => "Chinna",     :location => "Bangalore, India",     :image => "http://si0.twimg.com/sticky/default_profile_images/default_profile_2_normal.png",     :description => "a very normal guy.",     :urls => {       :Website => nil,       :Twitter => "https://twitter.com/chinna"     }   },   :credentials => {     :token => "a1b2c3d4...", # The OAuth 2.0 a...

MONGODB COMMANDS

CREATE TABLE USERS (a Number, b Number)     Implicit or use MongoDB::createCollection(). INSERT INTO USERS VALUES(1,1) $db->users->insert(array("a" => 1, "b" => 1)); SELECT a,b FROM users $db->users->find(array(), array("a" => 1, "b" => 1)); SELECT * FROM users WHERE age=33 $db->users->find(array("age" => 33)); SELECT a,b FROM users WHERE age=33 $db->users->find(array("age" => 33), array("a" => 1, "b" => 1)); SELECT a,b FROM users WHERE age=33 ORDER BY name $db->users->find(array("age" => 33), array("a" => 1, "b" => 1))->sort(array("name" => 1)); SELECT * FROM users WHERE age>33 $db->users->find(array("age" => array('$gt' => 33))); SELECT * FROM users WHERE age<33 $db->users->find(array("age" => array('$lt' => 33))); SELECT * FROM use...

RSPEC WITH HAS_MANY AND BELONGS_TO ASSOCIATION TESTCASES FOR RUBY ON RAILS

Usermodel has_many :addresses, :dependent => :destroy Addressmodel belong_to :user describe User do    before(:each) do     @user_new = {:name => "chinna",:email => "chinna@yopmail.com",:password => "chinnaram",:password_confirmation => "chinnaram"}    end it "should create a new user details" do      @user_attr = User.create!(@user_new) end #validation for rspec has_many it "Should contain many Addresses" do     @user = User.new(@user_attr)     @user.addresses << Address.new(:user_id => @user.id)     @user.addresses << Address.new(:user_id => @user.id)     @user.should have(2).addresss end #dependent destroy for invitation it "should destroyed user addresss details" do    @user = User.new(@user_att)    user = User.new(:user_id => @user.id,:location =>"bangalore")    @user.destroy ...

OPTIONS FOR SELECT IN RAILS3

1)form_for with options for select in rails <%= f.select :user_id,options_for_select(User.find(:all).collect {|c| [ c.name, c.id ]},:selected => @user.name) %> 2)select_tag with options_for select with javascript <%= select_tag 'city', options_for_select([["Select name",'']]+@user.collect{ |u|[u.name, u.name] },@user.name), :data => { :remote => true, :url => url_for(:controller => "user", :action => "selected_user") } %>

Useful Links for rspec and cucumber and jquery and css and facebook app integration for Ruby on Rails..

Some important links for rspec and cucumber and jquery and css and facebook app integration for Ruby on Rails###################### ###########facebook links http://www.spritle.com/blogs/2012/02/08/facebook-canvas-app-using-ruby-on-rails/ https://developers.facebook.com/apps/209871355801368/summary?save=1 http://stephan.com/blog/really-easy-facebook-like-for-rails https://campus.tcs.com/campus/ #####cucumber testing......... http://blog.spritecloud.com/category/cucumber/ http://www.packtpub.com/article/facebook-application-development-ruby-on-rails http://blog.aentos.com/post/1114672143/testing-ajax-autocomplete-fields-with-cucumber-and http://asciicasts.com/episodes/186-pickle-with-cucumber http://rubydoc.info/github/jnicklas/capybara/master/Capybara /Node/Actions#click_button-instance_method https://github.com/cucumber/cucumber/wiki/Cucumber-Backgrounder https://github.com/jnicklas/capybara/ http://stackoverflow.com/questions/5794820/easy-way-to-test-nested-model-forms-with-cucumber...