Find Web browser user agent using rails 3


Hi friends,

In rails 3 there is a easy way to Detect the web browser user agent . 🙂

By adding the one line in the controller page, we can get the UA.(@user_agent = request.env[‘HTTP_USER_AGENT’])

In /app/controllers/users_controller.rb

def index
 @users = User.all
  @user_agent = request.env['HTTP_USER_AGENT']

In /app/views/users/index.html.erb

<%= @user_agent %>

That’s All !!!  🙂 🙂 🙂

GitHub Link: https://github.com/thasuresh/find_user_agent

Live Example On Heroku: http://findua.heroku.com/

Ex snaps for various Web browsers:

This slideshow requires JavaScript.

Advertisements

Multiple File uploading in Rails3 Application using “Papercilp”


Hi friends,

Lets see how to upload multiple files in a rails 3 application.

First create a new rails project and go inside of the project directory.

$ rails new fileuploading
$ cd fileuploading

Add the Gms in  following “Gemfile”

gem ‘nifty-generators’
gem ‘paperclip’


source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'nifty-generators'
gem 'paperclip'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'.....

And  bundle install it.

Now we have to create a scaffold. Do a following commands.

 $ rails g nifty:scaffold Post title:string
 $ rails g nifty:layout

It asks a Permission to Overwrite the layout file. just press “y”.  It shoes like,
Overwrite /home/suresh/deal_projects/paperclip-test/app/views/layouts/application.html.erb? (enter “h” for help) [Ynaqdh]

Again migrate with db.

 $ rake db:migrate
 $ rm public/index.html
Then, Add the following line in  your /config/routes.rb , root :to => “posts#index”
Then, create a model called “Asset”
$ rails g model Asset asset_file_name:string asset_content_type:string asset_file_size:integer asset_upload_at:datetime post_id:integer
$ rake db:migrate

Now in model folder, there is a file called “asset.rb”. Add the following lines into this file.

class Asset < ActiveRecord::Base
belongs_to  :post
has_attached_file  :asset, :styles => {  :large => "640*480",  :medium => "300*300>",  :thumb => "100*100>" }

end

And add the following lines into “posts.rb” file

class Post < ActiveRecord::Base
attr_accessible :title, :content,  :assets_attributes
has_many  :assets
accepts_nested_attributes_for  :assets,  :allow_destroy  => true
end

Edit app/controller/posts_controller.rb (Note the new and edit part)


def new
@post = Post.new
5.times { @post.assets.build }

end

def edit
@post = Post.find(params[:id])
5.times { @post.assets.build }
end

Edit and add the following lines in your app/view/post/_form.html.erb

<%= form_for @post, :html => { :multipart => true } do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>

<% f.fields_for :assets do |asset_fields| %>

<% if asset_fields.object.new_record? %>
<p>
<%= asset_fields.file_field :asset %>
</p>

<% end %>
<% end %>

<% f.fields_for :assets do |asset_fields| %>
<%unless asset_fields.object.new_record? %>

<p>

<%= link_to image_tag(asset_fields.object.asset.url(:thumb)), asset_fields.object.asset.url(:original) %>

<%= asset_fields.check_box :_destroy %>
</p>

<% end %>
<% end %>

<p><%= f.submit %></p>
<% end %>

That’s All .

In tour terminal run ” rails s” command and open the “http://localhost:3000” in your browser. 🙂

Selecting the files

Uploaded into project 🙂

GitHub Link:  https://github.com/thasuresh/fileuploading
 
My hearty thanks to: http://www.emersonlackey.com/article/paperclip-with-rails-3
 
 

Google maps in Rails3 Application — Sample Application


Hi friends,

(New update: For new version(0.9.1) check Jay’s comment below)

(Update: this tutorial works only on gem version 0.7.7 and won’t work on latest gem version 0.8.7)

Using a gmaps4rails gem to display a map in our application

create a rails application using,

$ rails new gmaps

$ cd gmaps

Add this Gem in your Gemfile

gem ‘gmaps4rails’, ‘0.7.7’

Now bundle it ($ bundle install )and migrate with db ( $ rake db:migrate)

Create a scaffold using,

$ rails g scaffold Location name:string address:string longitude:float latitude:float

remove the longitude and latitude fields in _form.html.erb

After that, add this in app/view/layout

<%= yield :head %> (in your header) <%= yield :scripts %> (in your footer)

/app/views/layouts/application.html.erb

<html>
<head>
  <title>Googlemap</title>
  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
  <%= yield :head %>
</head>
<body>
<%= yield %>
<%= yield :scripts %>
</body>
</html>

In model /app/models/location.rb to add

class Location < ActiveRecord::Base
 acts_as_gmappable
      def gmaps4rails_address
          address
      end
       def gmaps4rails_infowindow
         "<h4>#{name}</h4>" << "<h4>#{address}</h4>"
     end
end

add the line in controller /app/controllers/locations_controller.rb

def index
    @locations = Location.all
    @json = Location.all.to_gmaps4rails
    ..........

In your view app/views/locations/index.html.erb to add a last line as

<%= gmaps4rails(@json) %>

then start the server(http://localhost:3000/locations) to put the name and address, longitude and latitude as set automatically, then will be show the markers as corresponding address and click the marker icon.it will shows infowindow as name and address

That’s it!! If you have any questions please feel free to contact me. I will be happy to help where I can.  🙂

Map View

My Sample Application:

http://gmaps4rails.heroku.com

GitHub:

https://github.com/thasuresh/gmaps_project

Ref Link:

http://www.youtube.com/user/TheApneadiving

Sending One Time Password via SMS Using Rails3 and SMSAPI


Hi friends,

My need was send one time password via e-mail/sms ,who registered with their E-mail/mobile no.

Lets see “How to send SMS using Rails3 application and smsAPI”

At first we need a smsapi to send SMS via Rails3 application. There is a site, which provides FREE API to send SMS via programming. So, here we need to register with your Domain and mail-id. They also provide codes for various languages 🙂

EX code for RUBY:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=YOUR_MESSAGE&senderid=YOUR_SENDERID&recipient=MOBILE_NUMBER')

We just modify the code, what ever our application needs,

require 'net/http'
require 'uri'
pass = "Hi+This+is+ur+one+time+passwd:" + rand(999999).to_s
mobile = ARGV.shift
url = "http://s1.freesmsapi.com/messages/send?skey=9600152989freesmsaPI&message=#{pass}&senderid=slash&recipient=#{mobile}"
Net::HTTP.get_print URI.parse(url)
Then create a new rails project using,
  $ rails new sms
Go to project directory using,
  $ cd sms
Create scoffold using,
  $ rails generate scaffold name:string phone:string
Now, we have to edit the user controller
  $ gedit /app/controller/users_controller.rb
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])

smspasswd

respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end
Now, we have to write a small def function into that “usres_controller.rb” file
# POST /users
# POST /users.xml
def create
@user = User.new(params[:user])

smspasswd  #Note this Function

respond_to do |format|
if @user.save
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end

def smspasswd
name = @user.name
pass = "Hi+#{name},+This+is+ur+one+time+passwd:" + rand(999999).to_s
phone = @user.phone
url = "http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=#{pass}&senderid=slash&recipient=#{phone}"
Net::HTTP.get_print URI.parse(url)

end
That’s all
Sample Application: http://send-sms.heroku.com
Download from GitHub link: https://github.com/thasuresh/sms
Note:
      But, This “freesmsapi” does not work with the numbers who activated DND support. 😦

Sending SMS via “freesmsapi.com”


Hi friends,

I found a site which sends sms via website and programs. http://freesmsapi.com.

They provides their own API and programing codes in ruby,python.php.java,c,c#., etc.,

First we have to signup with our own domain and register with mail-id and phone number. that’s all. 🙂

Ex code in ruby:


require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('<a href="http://s1.freesmsapi.com/messages/send?skey=8c0185641435ac8a43cf10230a1417ac&message=Password:7876&senderid=fsmsapi&recipient=9943239066" target="_blank">http://s1.<wbr>freesmsapi.com/messages/send?<wbr>skey=<wbr>8c0185641435ac8a43cf10230a1417<wbr>ac&message=Password:7876&<wbr>senderid=fsmsapi&recipient=<wbr>9943239066</wbr></wbr></wbr></wbr></wbr></wbr></a>')

Now i’m trying to integrate this code into rails3 🙂

How to Send a mail using Gmail account with Rails3, ActionMailer and SMTP


Hi friends,

Action Mailer:

Action Mailer is a framework for building e-mail services. You can use Action Mailer to receive and process incoming email and send simple plain text or complex multipart emails based on flexible templates.

Lets see how to setup the actionmailer with Gmail SMTP.

First we have to create a rails application using

   $ rails new action_mailer

Next we’ll generate a scaffold for a User model with name and email attributes to act as a simple user-registration page.

$ rails genetate scaffold user name:string email:string

Now we have to migrate with DB.

$ rake db:migrate

The generated scaffolding code includes a page for creating users. We want to create a new user and then send them a confirmation email when the form on this page is submitted.

Now, just run the rails server command,

$ rails s

Then, open the “http://localhost:3000

Adding New User

The first thing we’ll do is create a new initializer file called setup_mail.rb and put some configuration options in it. ActionMailer will use sendmail if it’s set up on your machine but we can instead specify SMTP settings in the initializer.

  $ cd /config/initializers/

  $ gedit setup_mail.rb

ActionMailer::Base.smtp_settings = {  
      :address              => "smtp.gmail.com",  
      :port                 => 587,  
      :domain               => "gmail.com",  
     :user_name            => "thasuresh", #Your user name
      :password             => "actionmailer", # Your password
      :authentication       => "plain",  
      :enable_starttls_auto => true  
   }

You’ll probably want to use a different approach in a production application but this is a good enough approach while our application is in development. Obviously you’ll want to change the domain, user_name and password options to suit your own Gmail account.

Now that we’ve completed the configuration we can generate a new mailer with the following code:

  $ rails generate mailer user_mailer

$ cd /app/mailer

  $ gedit user_mailer.rb


class UserMailer < ActionMailer::Base
default :from => "thasuresh@gmail.com"

def registration_confirmation(user)
mail(:to => user.email, :subject => "Registered")
end
end

Now we have to create a file called registration_confirmation.text.erb under app/views/user_mailer.

  $ gedit app/views/user_mailer/registration_confirmation.text.erb

Thank you for registering!

/app/controllers/users_controller.rb  (Note the 6th line)


def create
@user = User.new(params[:user])

respond_to do |format|
if @user.save
UserMailer.registration_confirmation(@user).deliver  #include this line in your users_controller.rb file
format.html { redirect_to(@user, :notice => 'User was successfully created.') }
format.xml  { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end

mail sent by "ActionMailer"

If you want add user name at the mail, add the following line into registration_confirmation.text.erb

/app/views/user_mailer/registration_confirmation.text.erb.

<%= @user.name %>,

Thank you for registering!

Added User name

Now if you want add any attachments in the mail add this line into /app/mailer/user_mailer.rb


def registration_confirmation(user)
@user = user
attachments["rails.png"] = File.read("#{Rails.root}/public/images/rails.png")
mail(:to => "#{user.name} <#{user.email}>", :subject => "Registered")
end

Here my need is send a numeric password, when a user subscribe with his mail id. The password will send by actionmailer. So i added the a single ruby command into


Hi <%= @user.name %>,

This is the one time password, You can login into our site using the password given below

Password: <%=rand(999999)%>

Thank You For Registering!

Final output 🙂

That’s all !!!

Here sample “actionmailer” application and which deployed in heroku http://actionmailer.heroku.com

GitHub Account link: https://github.com/thasuresh/action_mailer