jump to navigation

rake aborted: no such file to load mysql September 24, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , , , , , , ,
6 comments

Programmers who work mostly on windows have seen this kind of errors many times.. as a windows programmer I have been through many sites and collect d relevant data, now I am showing it to you..

The errors which might come to you something like this:
no such file to load mysql
rake aborted: no such file to load mysql
The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql
Could not find RubyGem rake-compiler (~> 0.5)

To solve such problems follow these steps:
Step 1. Update rubygems to the latest version(like I upgraded it to 1.3.5).
Step 2: install rake-compiler(by gem install rake-compiler).
Step 3: if already installed hoe gem update it(gem update hoe) or install a fresh one.
Step 4: Download libMySQL.dll from here and copy it into C:/ruby/bin or wherever your ruby is installed, but make sure it should be in bin directory.
Step 5: Stop the mysql service, from Control Panel -> Administrative tools -> services -> mysql, and then restart it.

That’s it. You are done, after all these steps you can try
rake db:migrate
Suppose if that doesn’t work then after 4th step, stop the mysql service and restart your system.

I welcome all of you to post your comments, feedbacks, queries

Cheers!!
Puneet Pandey

Send Tweets from rails application August 12, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , ,
add a comment

Hey all,

I hope this article will help you if you want to send tweets from your rails application. I have used couple of gems and plugins for that, will describe you those in this tutorial.

AIM: We have a rails application which will allow twitter user to log-in. Once the user logged-in he/she can send tweets from your rails application.

DEPENDENCIES: 1. geokit-rails [Plugin]
2. ym4r-gm [Plugin]
3. twitter4r [Gem]
4. twitter-search [Gem]
5. twitter-console [Gem]
6. google-geocode [Gem] [Optional]

INSTALLATION:
1. Install twitter4r (gem install twitter4r[for windows user], sudo gem install twitter4r[for linux users])
2. Install twitter-search (sudo gem install dancroak-twitter-search -s http://gems.github.com)
3. Install twitter-console *for linux users only
[Follow this: http://www.fsckin.com/2008/03/31/twitter-clients-for-linux/]
[and this: http://blog.guillermoamaral.com/2007/03/18/twitter-console-update/]
4. Install google-geocode (sudo gem install google-geocode)
5. Install goekit-rails
5.1 ruby script/plugin install git://github.com/andre/geokit-rails.git
5.2 Add this line to your environment.rb: config.gem “geokit”
5.3 Tell Rails to install the gem: rake gems:install
(for more details visit this link: http://github.com/andre/geokit-rails/tree/master)
6. Install ym4r_gm (ruby script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/trunk/ym4r_gm)
[if you get trouble in installation follow this: http://ym4r.rubyforge.org/]

So we have a base setup for our rails application. Now lets have some code.
First of all lets create few models as well as migrations tables:
1. ruby script/generate model Keyword
2. ruby script/generate model Location
3. ruby script/generate model Post
4. ruby script/generate model User
5. ruby script/generate model Techtwit
6. ruby script/generate migration sessions

After creating all the above steps lets create some columns for our tables:
1. for keywords: timestamps
2. for locations: address:text, timestamps
3. for posts: message: text, timestamps
4. for users: username:string, password:string
5. for techtwits: twitter_id:string, timestamps
6. for sessions: session_id:string, data:text, timestamps
6.1 add_index :sessions, :session_id
6.2 add_index :sessions, :updated_at

Follow this Tutorial to finish-off this application.

Minimise URL in Ruby July 27, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , , , ,
1 comment so far

Does it looks odd?? You have so many websites which allows you to minimise your url like tinyurl, bit.ly etc etc list is endless, but what if you get some API of those to work with so you can minimise the url with your rails application or as a stand-alone ruby program??

Bit.ly comes with that. It provides ruby programmers an interface by which they can minimise the url. Wondering How? see it in action..

I am creating a simple ruby program here, if you want you can use it in your application…

All you need is json and open-uri to finish it off.

require ‘open-uri’
require ‘json’

code=’https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=zpwhtygjntrz&scc=1&ltmpl=default&ltmplcache=2&hl=en’
user=’YOUR USERNAME’
apikey=’YOUR API KEY’
version=’2.0.1′
url = “http://api.bit.ly/shorten?version=#{version}&longUrl=#{code}&login=#{user}&apiKey=#{apikey}”
buffer = open(url, “UserAgent” => “Ruby-ExpandLink”).read
result = JSON.parse(buffer)
shorturl = result['results']['shortUrl']

That is it. Run this program in console/command prompt, where ever you want to see the output.

Post your queries, suggestions
Puneet

Bulk Upload with Rubyzip July 27, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , ,
2 comments

Hi guys,

Its been a long time since I posted any article. This time I come up with Interesting Tutorial which is Bulk Upload. Normally in most of the sites we have seen that there is a file upload field where we can upload a zip file and it will extract automatically.

Now the Point is How it can be done is Ruby on Rails? The answer is very simple, all we need are two gems + few lines of code. Wondering How?? See this in action…

Install two gems first:

for Linux Users:

1. sudo gem install rubyzip

2. sudo gem install fastercsv

for windows users: remove sudo and install above gems.

now open up your rhtml page and write down the following code:

<% form_for :file_upload,:url => {:controller=>'bulkupload',:action=>'upload_file'}, :html => { :multipart => true, :target => "frame", :id => "file_upload" } do |f| %>
<input type="file" name="file_upload_product[file_name]"/>
<input type="submit" value="Upload"/>
<%end%>

Now Open up your bulkupload controller and create method upload_file in that

require 'faster_csv'
require 'fileutils'
class BulkuploadProductController < ApplicationController
  def bulk_upload
    begin
     @file=FileUpload.new
     @file.file_name=params[:file_upload_product]['file_name']
     if @file.save
      responds_to_parent do
       render :update do |page|
        page << "$('file_uploaded_id').value="+@file.id.to_s
        page.replace_html 'upload_message',"<span class='heading4'>File has been moved to server. Please click submit to upload.</span>"
       end
      end
     else
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Please Upload File</span>"
       end
      end
     end
     rescue Exception=>e
      puts "ERROR :: bulkupload_products :: upload_file :: #{e.to_s}"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Some internal Error has occurred</span>"
       end
      end
    end
  end
end

Let me know if you have any doubts

Fetch Rss Feeds in Rails March 2, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , ,
add a comment

Heya Guys,

Gossshh, I had lot of work, woooooohhh, but now I am over with that and thought to write a new post for all of you… I am very thankful to all of you that you are appreciating my articles and giving me such a good response, It is not only developing my confidence but also I want to bring more and more articles in rails, so that It will help you to know the magic behined RoR.

So let me start it. In this post of mine I will Fetch Rss Feeds from Techcrunch with open-uri, Interested to know, let’s see how it works…

Create an application, open your environment.rb file and add this line at the bottom:
RSS_FEED = ‘http://feedproxy.google.com/TechCrunch’

Now create a controller, in my case I have feeds_controller with fetch method, Open it and add below lines
class FeedsController < ApplicationController
require ‘rss/2.0′
require ‘open-uri’
def fetch
feed_url = “#{RSS_FEED}”
count = 50.to_i
output = “

Rss Reader


open(feed_url) do |http|
response = http.read
result = RSS::Parser.parse(response, false)
output += “Reed Title: #{result.channel.title}

result.items.each_with_index do |item, i|
output += “#{i+1}. ‘#{item.title}’
” if i output
end
end

You are almost done guys, now open up your views/feeds/fetch.html.erb and write a single line:

That is it. You are done.. start your server and you should see all the feeds there…
like this:

Rss Feeds

Rss Feeds

Don’t forget to drop me your inputs, suggestions, feedback on this..

With Love
Puneet

Add Default Image with Attachment_fu Plugin January 7, 2009

Posted by Puneet Pandey in Ruby On Rails.
Tags: ,
add a comment

Hi Guys,

Hope you all are fine and doing good. My Run Time Experiences bringing more and more posts.
Last Week I was stuck in a Big problem. I am using attachment_fu in my application. Although its a great plugin for file uploading. But I faced couple of problems like :
I m taking example of User_Profile model so there is a user_profiles table in the Db.

(1) Suppose If user left uploaded_data field blank, Next time when user updates the table value and this time also he/she left the field blank, then the Plugin shows me an error.

(2) When User left the uploaded_data field blank while creating user_profile and then try to delete his/her profile. The Plugin gives error something like this :

Can’t Convert nil to String

Now there are two ways to solve this:

(1)  Suppose your user model has_one user_profile. Then in your models/user.rb you can write something like this :

User.rb
has_one :user_profile, :dependent => :destroy

This will work for most of the cases but suppose if you want that if user has left the field blank there should be a default image which would go into the database. So for this in your model user_profile.rb write a method.

def add_default_image
self.content_type = ‘image/png’
self.filename = ‘personal-256.png’
self.temp_path = “#{RAILS_ROOT}/public/images/personal-256.png”
end

make sure that this image is present in your images folder.

Now you need to validate if params[:uploaded_data] is blank or not, suppose my action comes to create method, so do something like this :

def create
@user_profile = UserProfile.new(params[:user_profile])
if params[:user_profile][:uploaded_data].blank?
params[:uploaded_data] = @user_profile.add_default_image
@user_profile.save!
redirect_to(“Some Action”)
flash[:notice] = “Profile has been saved..”
else
if @user_profile.save
redirect_to(Some Action)
flash[:notice] = “Your contact has been saved successfully”
else
render :action => ‘new’
flash[:error] = “There is some problem saving the user”
end
end
end

Your Image should appear to you even if you left the params of uploaded_data blank. I think basics of attachment_fu you all can handle.

Cheers :)

Problem in Installing Contacts GEM in Windows December 23, 2008

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , , ,
10 comments

hey guys,
In this post of mine, I will show you how to install ‘contacts’ gem in your windows machine.

God, I searched google a lot for this and at last I found something interesting which I want to tell you.

I was working on linux, I switched to windows recently. During my project I thought to install contacts which will import my contacts from Gmail, Yahoo and Hotmail. When I write in command prompt:
C:\> gem install contacts

it gives me the following error

nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6
for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6/ext/gem_make.out

I think lots of you have seen this kind of error, Now I am telling you the steps how to solve this
Concentrate on line this :

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6

Now go to this Url
http://rubyforge.org/frs/?group_id=1028
and install the latest ferret gem having mswin32 version. Install it and run it, I think all of you know how to install gem manually :)

Then try to install contacts gem, It will run.
Just in case if it gives error again like this:

nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.

Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3 for
inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3/ext/json/ext/parser/
gem_make.out

Then go to this url:
http://rubyforge.org/frs/?group_id=953
and download the latest mswin32 gem of json and install it. After installing it try to run

gem install contacts

Your gem should install.

Generate XML with Rails December 8, 2008

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , , ,
4 comments

Hello All,
Happy New Year in Advance, In this post of mine, I will generate XML with Buildergem. Here is how to do this:
go to terminal, in my case I m generating a new application.
–> rails myapp
go into the directory and type
–> mysql -u root -p
This will open mysql query browser in the terminal itself, create a new schema
–> create schema myapp_development;
type –> exit and get out from terminal, open your –> database.yml and change it according to that.
Now, generate a model Address by this:
–> ruby script/generate model Address
now open your addresses.rb from db/migrate folder and add following lines
–> t.string :name
t.string :city
One thing to be noted here, I m using acts_as_authenticated plugin, so I have added user_id also in that, so that It will be easy for me to generate XML for the current_user i.e the logged in user.
run –> rake db:migrate
if you have builder gem installed open up environment.rb file from config folder and add
–> require ‘builder’
after the end the ‘end’ line.
If you don’t have builder, you can easily install it by typing
–> sudo gem install builder
I think you guys are able to generate rhtml pages of it, now let’s see the controller action:
–> def new
@address = Address.new
end

screenshot

from here my action goes to generate, see how gen_xml will store data.

–> def generate
@address = Address.new(params[:address])
@address.user_id = current_user.id
if @address.save
redirect_to :action => ‘gen_xml’
end
end
values of address are saved, let’s see our new action i.e gen_xml

–> def gen_xml
@xml = Builder::XmlMarkup.new
@addresses = Address.find(:all, :conditions => ["user_id = ?", current_user.id])
render :layout => false
end
Here Builder is your gem and it will generate XmlMarkup, here I m giving render :layout => false, coz I want to display generated XML without any CSS. Now your next step will be to create a file in your controller name gen_xml.rxml and add the below code:

–> xml.instruct! :x ml, :version=>”1.0″
xml.declare! :D OCTYPE, :html, :P UBLIC, “-//W3C//DTD XHTML 1.0 Strict//EN”, “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”

xml.addresses{
for address in @addresses
xml.address do
xml.name(address.name)
xml.city(address.city)
end
end
}
that’s it you are done, below is the screenshot of what I have done:

screenshot-2

If you find any problem or if you have done it successfully, please leave a comment. It will give boost up my confidence level.

Thanks

Ruby on Rails Interview Questions October 3, 2008

Posted by Puneet Pandey in Ruby On Rails.
Tags: , , ,
27 comments

Hi Guys, Hope you all are fine, Well I think that I should Post something different in my blog, so that It will help you to get some more knowledge :) , So I came with Interview Questions, Hope this will help you a lot, I will update it regularly, If I found something Interesting. Well If you are experienced, I hope this should help you. All the Questions are dynamically Typed.

Q1. What is request.xhr?
Sol: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE

Q2. What is the Difference between Static and Dynamic Scaffolding?
Sol: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.

Q3. What is the Difference between Symbol and String?

Q4. What is Session and Cookies?
Sol: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “puneet” it remains when the browser is not closed

Q5. Why Ruby on Rails?
Sol: There are lot of advantages of using ruby
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept

Q6. What is MVC? and how it Works?
Sol: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this: Request first comes to the controller, controller finds and appropriate view, your view interacts with model, model interacts with your database, for Example your url is something like this:

http://localhost:3000/users/new

here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.

Q7. What things we can define in the model?
Sol: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql

Q8. What is ORM in Rails?
Sol: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.

Q9. How many Types of Relationships does a Model has?

Q10.  What is the difference between rails version 2.2.2 with the older ones?

Q11. Difference between render and redirect?
Sol: render example: render :action, render :partial etc.
redirect example: redirect_to :controller => ‘users’, :action => ‘new’

Q12. How to use sql db or mysql db. without defining it in the database.yml
Sol. http://stuff.lilleaas.net/active_record_anywhere

Q13. What are helpers and how to use helpers in ROR?
Sol. Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.

Q14. What is Active Record?
Sol. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table

Q15. Ruby Supports Single Inheritence/Multiple Inheritence or Both?
Sol. Ruby Supports only Single Inheritnece

Q16. How many types of callbacks available in ROR?
Sol. * (-) save
* (-) valid
* (1) before_validation
* (2) before_validation_on_create
* (-) validate
* (-) validate_on_create
* (3) after_validation
* (4) after_validation_on_create
* (5) before_save
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save

Q17. Suppose in one of my method I am updating the attributes of table, in my model I have defined after_create do X, and after_save do Y. Which method will be called?

Ruby Interview Questions :

Q1. How to use two database into a Single Application?
Sol. http://magicmodels.rubyforge.org/magic_multi_connections/, According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.

screenshot

To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link : http://magicmodels.rubyforge.org/magic_multi_connections/

Q2. What is the Notation used for denoting class variables in Ruby?

Q3. What is the use of Destructive Method?

Q4. What is the use of load and require in Ruby?

Q5. What is the use of Global Variable in Ruby?

Q6. How does nil and false differ?

Q7. How is visibility of methods change in Ruby?

Q8. What is a Class Instance Variable

Q9. What are the rules and conventions to be followed in Ruby for naming a method?

Q10. What is the use of Super?

Q11. How is class method defined in Ruby?

Q12. What are the Operators available in Ruby?

Q13. What are the looping structure available in Ruby?

Q14. What is the scope of local variable?

Q15. What are the OOP supported by Ruby?

Q26. If Ruby over PHP, Why?

Q17. Garbage collection in Ruby?

Q18. Environment Variables in Ruby?

Q19. What are Float, Dig and Max?

Q20. What is Ruby Code blocks?

Q21. What kind of conditions ruby support?

Q22. Difference between puts and print

More Questions and Answers of this will be published very soon :) So stay in touch.. I will keep you updating.. if you have some questions please reply…