Monday, June 20, 2011

ruby 1.9.2 restful_authentication plugin unknown encoding name: mule-utf-8 issue

The issue
=> Booting WEBrick
=> Rails 2.3.10 application starting on http://0.0.0.0:3000
C:/Users/project/vendor/plugins/restful-authentication/lib/authentication/by_cookie_token.rb:1: unknown encoding name: mule-utf-8 (ArgumentError)
from :29:in `require'
from :29:in `require'


To fix this
replace line no 1 (# -*- coding: mule-utf-8 -*-) of /vendor/plugins/restful-authentication/lib/authentication/by_cookie_token.rb
with # -*- coding: utf-8 -*-

Monday, May 16, 2011

Wednesday, March 16, 2011

Zip multiple files and download as attachment using rubyzip gem.

rubyzip is a lib for creating / working with zip archives in ruby.

» gem install rubyzip


Sample code

require 'zip/zip'
require 'zip/zipfilesystem'


def download_all
attachments = Upload.find(:all, :conditions => ["source_id = ?", params[:id]])

zip_file_path = "#{RAILS_ROOT}/uploads/download_all.zip"


# see if the file exists already, and if it does, delete it.
if File.file?(zip_file_path)
File.delete(zip_file_path)
end


# open or create the zip file
Zip::ZipFile.open(zip_file_path, Zip::ZipFile::CREATE) { |zipfile|

attachments.each do |attachment|
#document_file_name shd contain filename with extension(.jpg, .csv etc) and url is the path of the document.
zipfile.add( attachment.document_file_name, attachment.document.url)

end

}
#send the file as an attachment to the user.
send_file zip_file_path, :type => 'application/zip', :disposition => 'attachment', :filename => "download_all.zip"

end

Monday, January 3, 2011

Thinking Sphinx Issue: Connection to Sphinx Daemon (searchd) failed

Thinking Sphinx may will not work when rails files path has spaces in it, so "My Documents" or "firstname lastname" will not work.
So either create a new directory under c:\ and then sphinx.yml folder into rails config folder and add these into it
development:
    bin_path: C:/Sphinx/bin
    config_file: C:/Users/projects/rails_app/config/development.sphinx.conf

You can also create a new account and then make sure if all the path is set in environment variables.
and then if you follow the above instructions and if you try rake ts:index then thinking sphinx will work fine.

Friday, December 10, 2010

Read an article on rake tasks

It’s about Dependencies

This may be a bit of a stretch to say but build tools are about dependencies. One file or set of files depends on another set to get compiled, linked, or other fun things before the next set can be processed. The same idea exists in rake with tasks and task dependencies. Let’s look at a simple rake task. Save the following as “Rakefile” in any directory:

directory "tmp"

file "hello.tmp" => "tmp" do
sh "echo 'Hello' >> 'tmp/hello.tmp'"
end

What we’re saying here is that the file named “hello.tmp” depends on the directory "tmp". When rake runs across this, it’s going to create the directory "tmp" first before running the "hello.tmp" task. When you run it, you’ll see something like the following:

[jason@brick:~/src]$ rake hello.tmp
(in /Users/jason/src)
echo 'Hello' > 'tmp/hello.tmp'

If you were to look at the "hello.tmp" file you would see the phrase "Hello". What happens if you run it again? You’ll see the same output again. What’s going on? Rake is generating the file again. It’s doing this because it can’t actually find the file tmp/hello.tmp from that definition. Let’s redefine the task:

directory "tmp"

file "tmp/hello.tmp" => "tmp" do
sh "echo 'Hello' > 'tmp/hello.tmp'"
end

Now if you were to run it twice you would see something like this:

[jason@brick:~/src]$ rake "tmp/hello.tmp"
(in /Users/jason/src)
mkdir -p tmp
echo 'Hello' > 'tmp/hello.tmp'
[jason@brick:~/src]$ rake "tmp/hello.tmp"
(in /Users/jason/src)

Rake now knows that the file task has been run.
Running Other Tasks

Rake tasks can take the form of having prerequisites and can depend on another task. Let’s say I wanted to get ready in the morning. My process would be something like this:

1. Turn off alarm clock.
2. Groom myself.
3. Make coffee.
4. Walk dog.

Let’s further assume that I have OCD and have to do all of these in order. In rake I might express my morning as follows:

task :turn_off_alarm do
puts "Turned off alarm. Would have liked 5 more minutes, though."
end

task :groom_myself do
puts "Brushed teeth."
puts "Showered."
puts "Shaved."
end

task :make_coffee do
cups = ENV["COFFEE_CUPS"] || 2
puts "Made #{cups} cups of coffee. Shakes are gone."
end

task :walk_dog do
puts "Dog walked."
end

task :ready_for_the_day => [:turn_off_alarm, :groom_myself, :make_coffee, :walk_dog] do
puts "Ready for the day!"
end

If I were to run this as is I would type rake ready_for_the_day and I’d see the following:

[jason@brick:~/src]$ rake ready_for_the_day
(in /Users/jason/src)
Turned off alarm. Would have liked 5 more minutes, though.
Brushed teeth.
Showered.
Shaved.
Made 5 cups of coffee. Shakes are gone.
Dog walked.
Ready for the day!

By running the ready_for_the_day task it notices that the turn_off_alarm, groom_myself, make_coffee, and walk_dog tasks are all prerequisites of the ready_for_the_day task. Then it runs them all in the appropriate order. You’ll notice that we can pass something in to the make_coffee task. If we were having a really tough day we could pass in a value to the COFFEE_CUPS environment variable and be more prepared:

[jason@brick:~/src]$ rake COFFEE_CUPS=5 make_coffee
(in /Users/jason/src)
Made 5 cups of coffee. Shakes are gone.

Namespaces

Rake supports the concept of namespaces which essentially lets you group together similar tasks inside of one namespace. You’d then specify the namespace when you call a task inside it. It keeps things tidy while still being quite effective. In Rails, you might notice the db:migrate task. In that example, db is the namespace and migrate is the task. Using the above example, we might put everything in to the morning namespace:

namespace :morning do
task :turn_of_alarm
....
end

Now if you were to run rake COFFEE_CUPS=3 morning:ready_for_the_day you would have the same output as above, only it only took 3 cups of coffee today. Score!
The Default Task

Rake has the concept of a default task. This is essentially the task that will be run if you type rake without any arguments. If we wanted our default task to be turning off the alarm from the example above, we’d do this:

task :default => 'morning:turn_off_alarm'

Running rake now produces the following:

[jason@brick:~/src]$ rake
(in /Users/jason/src)
Turned off alarm. Would have liked 5 more minutes, though.

Describing Your Tasks

You can use the desc method to describe your tasks. This is done on the line right above the task definition. It’s also what gives you that nice output when you run rake -T to get a list of tasks. Tasks are displayed in alphabetical order. We’ll define some descriptions in our Rakefile (abbreviated for brevity):

...
desc "Make coffee"
task :make_coffee do
cups = ENV["COFFEE_CUPS"] || 2
puts "Made #{cups} cups of coffee. Shakes are gone."
end
...

Now when we run rake -T for our list of tasks we get the following output:

[jason@brick:~/src]$ rake -T
(in /Users/jason/src)
rake afternoon:make_coffee # Make afternoon coffee
rake morning:groom_myself # Take care of normal hygeine tasks.
rake morning:make_coffee # Make coffee
rake morning:ready_for_the_day # Get ready for the day
rake morning:turn_off_alarm # Turn off alarm.
rake morning:walk_dog # Walk the dog

You can add in a string to get tasks matching that displayed. Running rake -T af would show just the afternoon task.
Redefining Tasks

Let’s say you want to add on to an existing task. Perhaps you have another item in your grooming routine like styling your hair. You could write another task and slip it in as a dependency for groom_myself but you could also redefine groom_myself later on (shortened for brevity but you get the idea):

namespace :morning do
....
task :groom_myself do
puts "Brushed teeth."
puts "Showered."
puts "Shaved."
end
....
end
...
namespace :morning do
task :groom_myself do
puts "Styled hair."
end
end

[jason@brick:~/src]$ rake morning:groom_myself
(in /Users/jason/src)
Brushed teeth.
Showered.
Shaved.
Styled hair.

Invoking Tasks

You may at some point want to invoke a task from inside another task. Let’s say, for example, you wanted to make coffee in the afternoon, too. If you need an extra upper after lunch you could do that the following way:

namespace :afternoon do
task :make_coffee do
Rake::Task['morning:make_coffee'].invoke
puts "Ready for the rest of the day!"
end
end

Which outputs:

[jason@brick:~/src]$ rake afternoon:make_coffee COFFEE_CUPS=1
(in /Users/jason/src)
Made 1 cups of coffee. Shakes are gone.
Ready for the rest of the day!

A real world example of this is the rcov:all task. I use this in Genius Pool for aggregate rcov data. It’s shamelessly stolen from Clayton Lengel-Zigich. Go check out that post for a good example of invoking other tasks from rake.
Refactoring

You’ll notice in the example above we’re delegating most of the work to already defined methods and tasks in the RSpec and Cucumber classes. As a general rule, try to keep your methods already defined other places and call them from rake with your specific options and use cases. Let’s say I had a Rails application that e-mailed all accounts in the system that their account was expiring in a certain number of days. Here’s one way to write it:

namespace :accounts do
desc "Email expiring accounts to let them know"
task :email_expiring => :environment do
date = ENV['from'] ? Date.parse(ENV['from']) : Date.today
accounts = Account.find(:all, :conditions => ["expiration_date = ?", date]
accounts.each do |account|
Notifier.deliver_account_expiration(account)
end
end
end

A better way, that would let you test it more thoroughly would be to do the following:

namespace :accounts do
desc "Email expiring accounts to let them know"
task :email_expiring => :environment do
date = ENV['from'] ? Date.parse(ENV['from']) : Date.today
Account.notify_expiring(date)
end
end

This lets you unit test your notify_expiring method on the account class and make sure that it’s doing what it’s supposed to do. This is a small, made up example, but you get the idea. Here’s an example from Resque:

desc 'Restart redis'
task :restart do
RedisRunner.stop
RedisRunner.start
end

Notice the delegation to the RedisRunner class methods? This is a great rake task
Rails

You can get access to your models, and in fact, your whole environment by making tasks dependent on the environment task. This lets you do things like run rake RAILS_ENV=staging db:migrate. Rails will autmatically pick up tasks in lib/tasks. Any files named with the .rake extension will get picked up when you do rake -T.
Scheduling Rake Tasks

You can use cron to schedule rake tasks. Let’s say you wanted to run the account email expiration task every night at 12:15 on your production server, you might have something like this:

15 * * * * cd /data/my_app/current && /usr/bin/rake RAILS_ENV=production accounts:email_expiring

Misc

Rake.original_dir gives you the directory that the original rake task was run from.

Derivatives

* Thor is a more class based approach to solving some of the things rake does as far as actual tasks go.
* Capistrano is the de facto standard for deploying rails apps. Its syntax is inspired pretty heavily by Rake, but it is definitely not rake.

Source http://jasonseifer.com/2010/04/06/rake-tutorial

Paperclip issue " is not recognized by the 'identify' command."

I tried to upload an image an image (paperclip plugin and windows 7) and then i received the following errror
Avatar C:/Users/machine~1/AppData/Local/Temp/stream20101210-2576-p7vfu8-0.png is not recognized by the 'identify' command.

This was the error obtained as i had not installed imagemagick in my new machine. To fix this i download image magick from http://www.imagemagick.org/script/binary-releases.php
Installed it and then restarted my machine.

Saturday, October 30, 2010

Installing nokogiri for rails 3 app on Heroku

I wanted to install nokogiri gem defined in gemfile of my application on windows platform and i can see them installed when i do a git push heroku master.
But still i get an error saying no such file to load --nokogiri. My application on heroku gets crashed.

After many hours of research then i found these things below:

The problem was with Bundler gem and Bundler 1.0 Will Not Install Compiled Gems in UNIX When `bundle install` is Run in Windows.

When I run bundle install for my project under Windows, Bundler will generate a Gemfile.lock with the following for Nokogiri:

nokogiri (1.4.3.1-x86-mingw32)
nokogiri (1.4.3.1-x86-mswin32)

However, Gemfile.lock does not list the UNIX version nokogiri (1.4.3.1). I then checkin my Gemfile.lock into git and deploy a release to our Linux server. As part of our Cap script, the server runs bundle install --deployment. Upon doing so, there are four problems.

1. Bundler will not install the Nokogiri gem on the Linux server.
2. Bundler will list every other gem in its output, except for Nokogiri.
3. Bundler will say Your bundle is complete!, even though the Nokogiri gem was not installed.
4. Because Bundler does not exit with an error, Cap will deploy the app without Nokogiri being built, and the app errors out when a user tries a page that uses Nokogiri.

I believe this may also affect other compiled gems that have native mingw or mswin builds.

Solution: Remove your Gemfile.lock file and then do a repush.

Thursday, October 21, 2010

ERROR: Failed to build gem native extension whenever we install a gem on windows

When i tried to install a hpricot (gem install hpricot) then i received the following error

Building native extensions. This could take a while...
ERROR: Error installing hpricot:
ERROR: Failed to build gem native extension.

C:/Ruby187/bin/ruby.exe extconf.rb
checking for stdio.h... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.

Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=C:/Ruby187/bin/ruby


Gem files will remain installed in C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8
.2 for inspection.
Results logged to C:/Ruby187/lib/ruby/gems/1.8/gems/hpricot-0.8.2/ext/fast_xs/ge
m_make.out

---------------

To fix this all i did was gem install (gemname) --platform=mswin32 (gemname is hpricot in my case)

Friday, September 17, 2010

:select, joins, where parameters in ActiveRecord find of rails

Extracting distinct records from a table can be done using

@players = Player.find(:all).map{ |player| player.name }.uniq

Here it queries and gets all the records from the table and a ruby method is executed to get the distinct records which makes it a bad solution as far as performance is concerned.

A better way to do this is to use the :select parameter of the ActiveRecord find method

@players = Player.find(:all, :select => 'DISTINCT name')

few other examples of using :select

@players = Player.find(:all, :select => ‘name, sur_name, date_of_birth’)

instead of @players = Player.find(:all) if the table data is huge.
However Player.find(:all) will be faster for short lists because of the Rails cache.

Player.find( :all,
:select => Player.column_names.select {|col| col != "sur_name"})

Using "where" for join tables
@users = User.joins(:roles).where(:roles => { :name => [Role::ADMIN, Role::CLIENT_ADMIN]})

Friday, August 27, 2010

Mate Framework diagrams

One-way communication: from views to business logic

































Thursday, August 12, 2010

Few useful links to learn flex with mate framework

http://cookbooks.adobe.com/post_Simple_MVC_For_Flex___Air_using_Mate_Framework-17018.html
http://livedocs.adobe.com/flex/3/html/help.html?content=projects_7.html
http://mate.asfusion.com/page/downloads
http://mate.asfusion.com/page/documentation/getting-started

Wednesday, August 11, 2010

Read an article which was inspiring.

Don’t just have career or academic goals. Set goals to give you a balanced, successful life. I use the word balanced before successful. Balanced means ensuring your health, relationships, mental peace are all in good order.
There is no point of getting a promotion on the day of your breakup. There is no fun in driving a car if your back hurts. Shopping is not enjoyable if your mind is full of tensions.

"Life is one of those races in nursery school where you have to run with a marble in a spoon kept in your mouth. If the marble falls, there is no point coming first. Same is with life where health and relationships are the marble. Your striving is only worth it if there is harmony in your life. Else, you may achieve the success, but this spark, this feeling of being excited and alive, will start to die. ……………….

One thing about nurturing the spark - don't take life seriously. Life is not meant to be taken seriously, as we are really temporary here. We are like a pre-paid card with limited validity. If we are lucky, we may last another 50 years. And 50 years is just 2,500 weekends. Do we really need to get so worked up? …………….

It's ok, bunk a few classes, scoring low in couple of papers, goof up a few interviews, take leave from work, fall in love, little fights with your spouse. We are people, not programmed devices..... ...." :)

Wednesday, August 4, 2010

How to get the logged in user ip address in rails

ip_address = request.env['REMOTE_ADDR']

M4v format videos on Ubuntu Linux

Running railscasts videos in ubuntu linux

Go to system > Adminsitration > Synaptic package manager
search for gsstreamer and install them.

Friday, July 23, 2010

Few useful links for pdf generation in rails

http://www.accesspdf.com/pdftk/#packages

http://wiki.github.com/sandal/prawn/using-prawn-in-rails
http://railscasts.com/episodes/153-pdfs-with-prawn
http://wilsoncolab.com/blog/bryan/2008/11/30/writing-pdfs-with-ruby-on-rails-using-prawn-and-prawnto/
http://prawn.majesticseacreature.com/
http://www.cracklabs.com/prawnto/use

http://rdoc.info/rdoc/sandal/prawn-layout/blob/bcfac3efffb68a0b3c9f1007c1c1193443470afc/Prawn/Document

Thursday, July 15, 2010

Modifications in rails auto_complete plugin to pass id as param.

The auto_complete plugin explain in railscasts passes the selected name as param.
Rails Autocomplete
In most cases we want to pass the select value id instead of name.
To pass the id instead of name in the above link all we need to do is


<!-- categories/index.js.erb -->
<%= auto_complete_values @categories, :name, :id %>
<%= text_field_with_auto_complete :product, :category_name, { :size => 15 }, { :url => categories_path(:js), :method => :get, :param_name => 'search', :after_update_element => "function(text_field, li_element){$('product_category_id').value = $('text_' + li_element.id).value;}"}) %>
<%= hidden_field "product", "category_id" %>
 
<!-- application_helper -->
  def auto_complete_values(entries, text_field, value_field, phrase = nil)
    return unless entries
    items = entries.map do |entry|
      content_tag("li", phrase ? highlight(entry[text_field], phrase) : h(entry[text_field]), {:id => entry[value_field]}) +
      hidden_field_tag("text_#{entry[value_field]}", entry[value_field])
    end
    content_tag("ul", items.uniq, {:style=> "height: 150px; overflow:auto;"})
  end

Note: In case you want to trigger an event on select of autocomplete list then all you want to do is modify after_update_element
Ex: <%= text_field_with_auto_complete :company, :number, {:class => "title"}, {:url => autocomplete_company_numbers_path(:js), :method => :get, :param_name => 'search', :after_update_element => "function(text_field, li_element){window.location.href='/company__numbers/show/' + $('text_' + li_element.id).value;}"} %>

Tuesday, July 13, 2010

Using Clockwork and Delayed Job gem to send event reminder emails.

code below run a background process to send an event reminder emails.
Install clockwork and delayed_job gem. You might want to upgrade ruby gem version too
commands:
gem install clockwork
gem install delayed_job

Create Reminder model with event_id, reminder_at fields

class CreateReminders < ActiveRecord::Migration
  def self.up
    create_table :reminders do |t|
      t.integer :event_id
      t.datetime :reminder_at
      t.timestamps

    end
  end

  def self.down
    drop_table :reminders
  end
end


Add the association into Reminder model
belongs_to :event

Now create clock.rb in the lib folder of your application and add the following.

  require 'rubygems'
require 'clockwork'
include Clockwork

require 'config/boot'
require 'config/environment'
every(2.minutes, 'reminder.deliver') {
reminders = Reminder.find(:all, :conditions => ["reminder_at <= ? and reminder_at > ?", Time.now.advance(:minutes => 2), Time.now])
#reminders = Reminder.find(:all, :conditions => ["reminder_at <= ?", #Time.now.advance(:minutes => 2)])
unless reminders.nil?
UserMailer.send_later( :deliver_event_reminder, reminders )
end


Now using command prompt go to the root directory of the application and run the command
clockwork lib/clock.rb
If you are using delayed_job then you will have to  rake jobs:work in another command prompt
This will trigger an event every 2 minutes which will get all the reminders that needs to be send in the next two minutes and delivers it.

How to make your pc run as fast a new

STEP 1

For those who believe their computer lags at start up, a quick look at the MSConfig would be the place to start. MSConfig can be accessed by hitting the Windows button on keyboard along with R key.

This will bring up the 'Run' dialog. Type 'MSConfig' and you will get the 'Start Up' tab with a list of programs and executables that are launched when the computer starts up.

Starting up of too many programs when the computer boots could be a reason why the boot time is so long. The remedy would be to go through the entire list and uncheck the unnecessary items.

If there are entries you are not sure about, check them on the internet, as unchecking the wrong entries could potentially mess up the functionality of some of your programs.

STEP 2

Defragment the hard drive once a month. It's like changing your car's oil - it should be the one thing on your list even if you don't do anything else. Windows stores information about your programs in the Registry.

This can get cluttered and affect performance. The solution is to download free registry cleaners from the internet (eg CCleaner) to remove redundant program entries.

STEP 3

Indexing Services is a nifty little program that uses a large amount of RAM. This processes indexes and updates lists of files on your computer. This is done so that when you search for something, it can search faster by scanning the index lists.

So, if you don't search your computer often, turn it off would better performance. Simply go to 'Start' button on taskbar, click on 'Control Panel' and select 'Add/Remove Programs'. Find the tab 'Add/Remove Window Components' and uncheck 'Indexing Services'. Click Next.

Also, if there is a delay every time you open 'My Computer' to browse folders, try this.

Open 'My Computer', click on 'Tools', select 'Folder Options', click on the 'View' tab to uncheck the 'Automatically search for network folders and printers' box.

Click 'Apply' and then reboot your computer for changes to apply.

STEP 4

Hard drive performance plummets as you near the drive's maximum capacity.

Assuming you don't have an additional drive to move the content to, your choices are slim. But before you take a machete to your files, you may want to compress them.

Use the built-in compression tool in Windows, which makes accessing the files no different from it currently is. Go to 'Disk Cleanup' and make sure 'Compress Old Files' is checked.

Click 'Options' and specify the age of the files you want Windows to compress - Windows will compress only the files you haven't accessed in more than six months (or as specified).

STEP 5

An important feature of Windows is its ability to return system files to the state they were in earlier. Before tweaking, users can create a new 'Restore Point'.

Go to Control Panel>Performance and Maintenance>System Restore or Start-All Programs > Accessories > System Tools>System Restore and select 'Create a restore point'.

If it is left alone, this can consume a good portion of your disk space with unnecessary restore points.

By default, it uses up to 12 per cent of each of your drives and, even if you have a big hard drive, many extra restore points can slow down processes like virus checking, disk-defragmenting, etc.

Typically, how much space you should allot to system restore depends on your system (200 MB - the minimum allowed - will hold 5 or 6 restore points) and should suffice for average users.

STEP 6

Also, the Windows XP (and Windows Vista) computers have features like smooth animated menus and transparent windows.

These use processor resources, too, which means they can cause slowdown. Right-click the 'My Computer' icon and click 'Properties'.

Click the 'Advanced' tab and under 'Performance', click 'Settings'. Choose to switch off some of these effects and see the improvement in your PC's performance.

STEP 7

Accumulated dust in computer cases a reason for over-heated PCs. Dust gets into the ball bearings in the fan and cause the fan to stop working. This may lead to overheating of processor and permanent hardware failure.

It is less common, but static charges from dust can also be a threat. A layer of dust on a memory chip can cause static electricity to build up.

This can amount to electric charge, which discharges on to your motherboard or memory chip. The best way to stop dust from building up is to open the case on your PC and vacuum it.

We recommend never tweak without knowing how to return where you began

Wednesday, July 7, 2010