hits counter
  Create Free Blog | Random Blog »   Report Abuse | Login   

 
Oct
12
Filed Under (Rails) by nareshrana on 12-10-2009

If your application allows members of the public to sign up and create a new user account, to post comments or disussion posts, it’s important to maintain some control over the information they can enter.

Leaving usernames like admin, root, user or your domain name etc. is open for all who wil signup with your website service can cause misused by a malicious user ley say for “admin” can make unwanted changes which you dont want be unprotected.. you may wish to prevent anybody from using them.

Depending on your requirement and needs, there are a couple of ways this can be achived.. The most simple is to use an inbuild model validation validates_exclusion_of

validates_exclusion_of validates that the specified attributes does not match any of the values passed with the :in option.

class User < ActiveRecord::Base
validates_exclusion_of :username,
:in => ["admin", "root", "user", "twitter", "facebook"],
:message => “is not available”
end

In this example, anybody trying to create a new account with username “admin” will receive an error message reading “Username is not available”.

A disadvantage of this method is that validates_exclusion_of is a case-sensitive. If a member of the public creates a user account named “Admin” or “HandyRailsTips” then this record would pass validation.

Provided you don’t care whether the case is preserved or not, you can simply add a before_validation callback to downcase the username before validates_exclusion_of is called:

class User < ActiveRecord::Base
before_validation {|u| u.username.downcase! }

validates_exclusion_of :username,
:in => ["admin", "root", "user", "twitter", "facebook"],
:message => “is not available”
end

Oct
12

As of my previous post just explained the twitter integration locally, That is working like a charm but there is something which I have noticed that let say for i.e,

if you have logged in twitter and you call your callback url in address like “http://localhost:3000/twitter” so it will connect to twitter for login if you choose “Accept” the request for login it will login to twitter but if you “Deny” then the twitter login, it will throw the page for something like this,

twitter-callback-page-when-you-deny-login-to-twitter

If you click on the link of application name on this page, you would thrown to the page below:
that is “401:Unauthorized” its because when twitter accept to take the token in the session that time when you deny the connecting token to the development or production session so it will throw this,

The solution for this is very simple you need to add a check in your users controller in callback method at a first check,

if params[:denied]
redirect_to root_path
else
“your code”

It will make a call by checking the token for callback page if its find callback it will redirect to root_path means on homepage so 401:unauthorized is Gone..

Enjoy..

Share SocialTwist Tell-a-Friend 
Oct
12
Filed Under (Twitter) by nareshrana on 12-10-2009

Now a days, most of the web applications provides the twitter authentication, implemented with Twitter_auth, allows you to use the twitter authentication in you application,

One of my friend did it on server but i want to make it possible on locally, the following steps fulfill the requirements..

1) first create an application

rails twitterauth

2) You need to install the specified gams

ruby gem install thoughtbot-factory_girl
ruby gem install thoughtbot-shoulda

3) create a user migration and paste following in migration

ruby script/generate migration users

class Users < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :twitter_id
t.string :login
t.string :access_token
t.string :access_secret
t.string :remember_token
t.datetime :remember_token_expires_at
t.string :name
t.string :location
t.string :description
t.string :profile_image_url
t.string :url
t.boolean :protected
t.string :profile_background_color
t.string :profile_sidebar_fill_color
t.string :profile_link_color
t.string :profile_sidebar_border_color
t.string :profile_text_color
t.string :profile_background_image_url
t.boolean :profile_background_tiled
t.integer :friends_count
t.integer :statuses_count
t.integer :followers_count
t.integer :favourites_count
t.integer :utc_offset
t.string :time_zone
t.timestamps
end
end

def self.down
drop_table :users
end
end

4) Now Install the twitter_auth dependency, Modify your environment.rb file by adding

config.gem ‘twitter-auth’, :lib => ‘twitter_auth’

Then sudo rake gems:install

14) Now prepare the application

ruby script/generate twitter_auth

5) rake db:migrate

6) In order to work properly, your application(even for development mode) need to be registered on twitter. Visit Twitter apps and form with your informations.

create a twitter_auth.yml file in config folder, Twitter doesn’t accept the callback params from anyone, so you will need to provide oauth_callback as a callback in the configuration form.

You need to put the two keys in config/twitter_auth.yml file in appropriate parameters..

7) We are going to create a twitter controller with an index method.

ruby script/generate controller Twitter index

Twitter_auth uses the REST twitter api style, so to the logged user friend time line copy and paste this in twitter_controller.rb, and returns a Json array. (visit the twitter api wiki for more information.)

Before calling functions that need you to be logged in, you will have to use the login_required method on before_filter.

map.root :controller => “twitter”

8.) This code goes into twitter_controller.rb

before_filter :login_required
#This will Retreives the specified users friend timeline

def index
@tweets = current_user.twitter.get(‘/statuses/friends_timeline’)
logger.info @tweets
end

9) In your views/twitter/index.html.rb

<% @tweets.each do |tweet| %>
<% link_to(tweet['user']['screen_name'] + ‘:’ ‘http://twitter.com/’ + tweet['user']['screen_name'], :target => ‘_blank’) + tweet['text'] %>
<% end %>

10) Prepare your development environment

sudo nano /etc/hosts

11) then add an extra line

127.0.0.1 twitterauth.local

11) Finally add the site to apache

sudo nano /etc/apache2/site-enabled/twitterauth

12) Then copy(and modify) these lines on it

<’VirtualHost *:80′>
ServerName twitterauth.local
DocumentRoot “/home/[REPLACE WITH YOU PATH]/twitterauth/public”
RailsEnv development
RailsAllowModRewrite off
<’directory “/home/[REPLACE WITH YOU PATH]/twitterauth/public”‘>
Order allow,deny
Allow from all
<’/directory’>
<’/VirtualHost’>

13) Restart apache

sudo /etc/init.d/apache2/restart

14) ruby script/server, if you open http://localhost:3000/oauth_callback you should have something like this

Share SocialTwist Tell-a-Friend 

no such file to load — URI

I was getting this error when I shifted from windows machine to a linux.. I was just trying to run windows application in linux but I was getting this error.. I search a lot for this issue some of the discussion forums suggesting to install open-uri gem but guess what ? Its already install on my repository, I tried working on rake gems:install but that time couldnt find the actual solution…

I was working on rails 2.3.4 that time.. One day I had a chance to install the lower version rails version 2.2.2 in one of my application to test one plugin.. so i installed rails 2.2.2 version, co-incedently I thought Lets run that application which was giving me this error and Application Ran…

So conclusion of this issue can be,

  1. If you want to install any gem or plugin which is not supporting to your current rails version
  2. Updates of system gem would be great if your application support latest rails version
  3. You dont require open-uri, rest-open-uri or any gem to get rid down from this issue

v5vt2dqc8w

Oct
05
Filed Under (Rails) by nareshrana on 05-10-2009

‘will_paginate’ is one of the most widely used plugins in most of the rubyonrails projects. its an alternative of classic pagination method.. and much customizable…

How to install will_paginate

gem install mislav-will_paginate

There are some other method you can find it here.

Example Usage:

In controller

@post = Post.find(:all, order => “position asc”).paginate :page =>, :par_page => 10
where :per_page passes the number of post you want to display. You can change it according to your need 1-100 will_paginate defines it to be 30 by default,

In Views:

you can simply use,

<%= will_paginate @post %>

some advanced methods..

<% if @post.previous_page %>
<%= will_paginate @post, :page_links => false, :next_label => “”, :prev_label => image_tag(“/images/prev_arrow.png”, :border => “0″)%>
<% end %>

<% if @post.next_page %>
<%= will_paginate @post, :page_links => false, :next_lpabel => image_tag(“/images/next_arrow.png”, :border => “0″), :prev_label => “” %>
<% end %>

If we put page_links => false then it won’t display the actual pagination numbers 1,2,3… and next_label & prev_label => “” as null it won’t display Next and Prev labels..

Sep
29

I have worked with many plugins for attching & uploading files like attachment_fu, acts_as_attachment, file_column, Jaxi file upload, Uploadcolumn, attchment_manager etc., and many more other but I think they all have some limitations at a point somewhat like some plugins are providing only session support, some with java support, some of them only with multiple files upload, but paperclips is the plugin which all functionality is their to help you make to use the Uploding file to your application..

The solution is Paperclip plugin available to use as follows,

Install the plugin:
ruby script/plugin install http://github.com/henrik/paperclip.git/

Usage of plugin:

In your model,

class User < ActiveRecord::Base

has_attached_file :avatar,
:styles => {medium => “300×300″,
:thumb => “100×100″ }

end

In your Migration:
class AddAvatarColumnToUser < ActiveRecord::Migration
def self.up
add_column :users, :avatar_file_name, :string
add_column :users, :avatar_file_size, :integer
add_column :users, :avatar_updated_at, :datetime
#Optional:
add_column :users, :avatar_height, :integer
add_column :users, :avatar_width, :integer
end

def self
def self.down
remove_column :users, :avatar_file_name
remove_column :users, :avatar_content_type
remove_column :users, :avatar_file_size
remove_column :users, :avatar_updated_at
# Optional:
remove_column :users, :avatar_height
remove_column :users, :avatar_width
end
end

In your edit & new views:

<% form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
<%= form.file_field :avatar %>

<% end %>

In your controller:

def create

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

end

In your show view:

<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>

If the model has avatar_height and avatar_width columns:
<%= image_tag @user.avatar.url, :size => @user.avatar.size %>

Populate database:
rake db:migrate

Run Application:
ruby script/server

Download uploaded files locally using controllers and model:

In your users controller:
def avatars
user = User.find(params[:id])
style = params[:style] ? params[:style] : ‘original’
send_file user.avatar.path(style),
:type => user.avatar_content_type
end

In your model:
class User < ActiveRecord::Base
has_attached_file :avatar,
:styles => { :thumb => “300×300>”, :small => “100×100>” },
:path => ‘:rails_root/non-public/system/:attachment/:id/:style/:basename.:extension’,
:url => ‘/:class/:id/:attachment?style=:style’
end

Restart Application ruby script/server and go to page:
http://localhost:3000/users/:id/avatar

Protecting the uploaded files to anonymous download:

Include the following in your model:
class User < ActiveRecord::Base
has_attched_file :avatar,
:url => ‘:class/:id/:style.:extension’,
:path => ‘:rails_root/assets/:class/:id_partition/:style.extension’

validates_attachment_presence :avatar
validates_attachment_content_tyoe :avatar, :content_type => ['application/avatar',        'jpeg/avatar', mpeg/avatar]

If your are using any media content for upload to specify the minimum size for content:
validates_attachment_size :mp3, :less_then => 20.megabytes

def downloadable?(user)
user != :guest
end
end

This does the following:

  • Defines a User model that has a paperclip attchment called avatar
  • Configures the URL used to access the mpeg file, for example /users/1/king.jpeg
  • Configures the path where paperclip will store uploaded files ( for example: RAILS_ROOT/assets/users/000/000/001/king.jpeg where RAILS_ROOT is the path to the root directory of the rails app) – the importent thing here is that the files are stored outside of the /public directory
  • Defines a validation of the file types
  • Defines a downloadable method that can be used to implement user access rights to the avatars. For simplicity it just allows all logged in users to access the avatar, however you can replace the logic requires in your application..
Share SocialTwist Tell-a-Friend 
Sep
24
Filed Under (Rails) by nareshrana on 24-09-2009

For example: lets assume that we need to add a column ‘name’ in users table(User model). In this case generate a migration like:

    script/generate migration AddNameToUser name:string

Output:

    class AddNameToUser < ActiveRecord::Migration
       def self.up
          add_column :users, :name, :string
       end

       def self.down
          remove_column :users, :name
       end
    end

Here AddNameToUser plays the main role. ‘Add’ specifies the we want to add column(s) and ‘User’ separated by ‘To’ specifies the table.

Similarly, if we need to remove a column ‘role’ :

     script/generate migration RemoveNameFromUser name:string

Output:

    class RemoveRoleFromUser < ActiveRecord::Migration
       def self.up
          remove_column :users, :role
       end

       def self.down
          add_column :users, :role, :string
       end
    end

Here RemoveRoleFromUser plays the main role. ‘Remove’ specifies the we want to remove column(s) and ‘User’ separated by ‘From’ specifies the table.

Sep
23
Filed Under (Rails) by nareshrana on 23-09-2009

By Default, The rails architecture comes with the format,

map.connect ‘:controller/:action/:id’
map.connect ‘:controller/:action/:id.:format’

so one need to pass the id to make it available as record, but if I want to use the name for users.. instead of id then how do you that?

Take the following example:
http://www.mydomain.com/users/show/1

Now here, What’s ’show’? Who is ‘users’ 1? Don’t the user have name?
Let’s say their name is ‘Kingster’

Here’s how to make turn the aobve url string into:
http://www.mydomain.com/users/kingster

  1. Get the names of the database column storing your user’s names(Let’s say its ‘name’)
  2. In config/routes.rb add, somewhere above the default route:
    map.connect ‘users/:name’, :controller => ‘users’, :action: => ’show’
  3. Now, in users_controller, find def show and change it to:
    @user = User.find_by_name(params[:name])
  4. Lastly, all the id-based pointing to all the users needs to be updated to reflect the name-based change, Like the one your users list.html file.
    ’show’, :name => user.name
Sep
04
Filed Under (Rails) by nareshrana on 04-09-2009

Launching soon is a plugin that helps rails projects to manage a dedicated launching soon page before the actual launch date. The plugin also collects email from potential customers.

Installing a Rails plugin:

script/plugin install http://github.com/satish/launching_soon.git

Usage of Plugin:

1) First, include the LaunchingSoon in ApplicatinController:

class ApplicationController < ActionController::Base
include LaunchingSoon
end

2) Add following routes to your Applications routes.rb file:

ActionController::Routine::Routes.draw do |map|
map.resources :news_letter_subscribes, :o nly => [:create]
end

or alternatively run the following command

ruby script/generate launching_soon_routes

Sep
04
Filed Under (Rails) by nareshrana on 04-09-2009

A simple way to integrate a videos with your ruby on rails application,

A rails plugin that easily allows you to show video streams on your site.
Currently, YouTube and Vimeo streams are supported.

Not that #video_url is expected to be in these formats:

YouTube: http://youtube.com/watch?v=gEILFf2XSrM
Vimeo: http://www.vimeo.com/726135

How to install..

1) Install the gem
gem install mdarby-acts-as_video_fu

2) Require the gem in your config/environment.rb file
config.gem ‘mdarby-acts_as_video_fu’, :lib => ‘acts_as_video_fu’

Example Usage:

1) Generate a resource that includes the title:string and video_url:string attributes,
ruby script/generate scaffold Video title:string video_url:string

2) Add ‘acts_as_video_fu’ to your model
class Video < ActiveRecord:Base
acts_as_video_fu
end

3) Show the video’s thumbnail in any view you like,
<%= image_tag thumbnail_url(video) %>

4) Add the ‘display_video’ helper to show the full-sized video in any view you like,
<%= display_video(@video) %>

youtube download
Powered By Indic IME