Tuesday, May 8, 2012

Using bundle exec in Rails 3


1)bundle exec executes a command in the context of your bundle.
That means it uses the gems specified in your Gemfile. Much of the time, running bundle exec rake foo has the same results as if you just ran rake foo, especially if you have the same gems installed systemwide as in your Gemfile. However, some applications may specify different versions of gems than the ones you have installed systemwide, and may want those exact gems and versions to be able to run correctly. If you just run without bundle exec, you may get some weird errors.
Using bundle exec guarantees that the program is run with the environment specified in the gemfile, which hopefully means it is the environment that the creators of the program want it to be run in, which hopefully means it should run correctly no matter what weird setup you have on your computer.
It basically standardizes the environment under which the program is run. This helps avoid version hell and makes life much easier.
See http://gembundler.com/man/bundle-exec.1.html for more info.

Friday, May 4, 2012

Installing Chrome on Ubuntu

Run the following commands in terminal:


1) wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -

2) sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'


3) sudo apt-get update


4) sudo apt-get install google-chrome-stable

Tuesday, April 24, 2012

Rails 3 Ubuntu 11.10 Installing nokogiri (1.5.2) with native extensions

Issue:
Using bundler (1.1.3)
Installing nokogiri (1.5.2) with native extensions
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /home/user/.rvm/rubies/ruby-1.9.2-p318/bin/ruby extconf.rb
checking for libxml/parser.h... yes
checking for libxslt/xslt.h... no
-----
libxslt is missing.  please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----
*** 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
    --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=/home/ganesh/.rvm/rubies/ruby-1.9.2-p318/bin/ruby
    --with-zlib-dir
    --without-zlib-dir
    --with-zlib-include
    --without-zlib-include=${zlib-dir}/include
    --with-zlib-lib
    --without-zlib-lib=${zlib-dir}/lib
    --with-iconv-dir
    --without-iconv-dir
    --with-iconv-include
    --without-iconv-include=${iconv-dir}/include
    --with-iconv-lib
    --without-iconv-lib=${iconv-dir}/lib
    --with-xml2-dir
    --without-xml2-dir
    --with-xml2-include
    --without-xml2-include=${xml2-dir}/include
    --with-xml2-lib
    --without-xml2-lib=${xml2-dir}/lib
    --with-xslt-dir
    --without-xslt-dir
    --with-xslt-include
    --without-xslt-include=${xslt-dir}/include
    --with-xslt-lib
    --without-xslt-lib=${xslt-dir}/lib

Fix:
Do the following:
1) sudo apt-get install libxml2-dev
2) sudo apt-get install libxslt1-dev
and then
bundle install

Thursday, March 22, 2012

Update DelayedJob run_at to change daily emails send time

Below is just a sample code.
1) Create a table to track delayed jobs

class CreateTrackDelayedJobs < ActiveRecord::Migration
  def self.up
    create_table :track_delayed_jobs do |t|
      t.integer :delayed_job_id
      t.integer :user_id
      t.integer :item_id

      t.timestamps
    end
  end

  def self.down
    drop_table :track_delayed_jobs
  end
end




2)Sample code to send daily news letters

a) Add a rake task which can be run everyday

task :send_news_letters => :environment do
        items = Item.all
        items.each do |current_item|
          
            send_time = Time.zone.local(Date.today.year, Date.today.month, Date.today.day, hours, minutes)
            NewsLetter.send_at(send_time, :send_digest, curent_item.id)
        end

b)

class NewsLetter

 def self.send_in(time, method, *args)
        send_at time.from_now, method, *args
    end

    def self.send_at(time, method, *args)
        dj = Delayed::Job.enqueue Delayed::PerformableMethod.new(self, method.to_sym, args), 0, time
        track_dj = TrackDelayedJob.where("item_id = ?",args[0]).first
        if track_dj.nil?
            TrackDelayedJob.create(:delayed_job_id => dj.id, :item_id => args[0])
        else
            old_dj = Delayed::Job.find_by_id(track_dj.delayed_job_id)
            old_dj.destroy unless old_dj.nil?
            track_dj.update_attribute(:delayed_job_id, dj.id)
        end
    end

def self.send_digest(item_id)
#write your code to send digest.
end

end

c) When you want to update already set delayed job then

NewsLetter.update_delayed_job_time(item_id, time)

add this in NewsLetter class
def self.set_delayed_job_time(item_id, time)
   
        track_dj = TrackDelayedJob.where("item_id = ?", item_id).first
        dj = Delayed::Job.find_by_id(track_dj.delayed_job_id) unless track_dj.nil?
        unless dj.nil?
            #below code is required in case you want to convert hours and minutes
            #   time = "#{Date.today} #{hours}:#{minutes}".to_time           
            dj.run_at = time
            dj.save
        end
    end

end

Saturday, March 17, 2012

Rails - Install and starting memcached on windows

1) Download Memcached for windows and extract it.

2) Open the command prompt as administrator and then run the command (assuming
your memcached is in c:\memcached)

c:\memcached\memcached.exe -d install

(Incase you get the below error:
C:\Windows\System32>c:\memcached\memcached.exe -d install
failed to install service or service already installed
Please make sure your are running the command prompt as administrator
start>command prompt> right click it and run as administrator.)

3) Start the server by:
C:\Windows\system32>net start "memcached Server"
The memcached Server service is starting.
The memcached Server service was started successfully.

Saturday, March 10, 2012

Rails Resque + RuntimeError at /resque/overview ERR unknown command 'server' issue

Issue: RuntimeError at /resque/overview ERR unknown command 'server' on windows at localhost:3000/overview


Fix: Just do a 'gem cleanup resque' to remove older versions of resque and then 'bundle update'.

Friday, March 2, 2012

Rails 3 Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.

Issue:
Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes.
/home/user/.rvm/gems/ruby-1.9.2-head/gems/execjs-1.2.6/lib/execjs/runtimes.rb:46:in `autodetect'
/home/user/.rvm/gems/ruby-1.9.2-head/gems/execjs-1.2.6/lib/execjs.rb:5:in `'
/home/user/.rvm/gems/ruby-1.9.2-head/gems/execjs-1.2.6/lib/execjs.rb:4:in `'
/home/user/.rvm/gems/ruby-1.9.2-head/gems/coffee-script-2.2.0/lib/coffee_script.rb:1:in `require'


Fix:

Add gem ‘therubyracer’ into Gemfile and then do a 'bundle install'

Thursday, March 1, 2012

Running a specific migration file


1) Incase you want to run migration from a particular file then 
rails console>> require "db/migrate/20110210070832_create_companies.rb"
>> CreateCompanies.up
 
other ways:
 
rake db:migrate:up VERSION=my_version
rake db:migrate:down VERSION=my_version
 
 
 

Thursday, February 23, 2012

Installing mysql2 gem on Ubuntu

Issue:
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /home/user/.rvm/rubies/ruby-1.9.2-head/bin/ruby extconf.rb
checking for rb_thread_blocking_region()... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lmygcc... no
checking for mysql_query() in -lmysqlclient... 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
    --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=/home/user/.rvm/rubies/ruby-1.9.2-head/bin/ruby
    --with-mysql-config
    --without-mysql-config
    --with-mysql-dir
    --without-mysql-dir
    --with-mysql-include
    --without-mysql-include=${mysql-dir}/include
    --with-mysql-lib
    --without-mysql-lib=${mysql-dir}/lib
    --with-mysqlclientlib
    --without-mysqlclientlib
    --with-mlib
    --without-mlib
    --with-mysqlclientlib
    --without-mysqlclientlib
    --with-zlib
    --without-zlib
    --with-mysqlclientlib
    --without-mysqlclientlib
    --with-socketlib
    --without-socketlib
    --with-mysqlclientlib
    --without-mysqlclientlib
    --with-nsllib
    --without-nsllib
    --with-mysqlclientlib
    --without-mysqlclientlib
    --with-mygcclib
    --without-mygcclib
    --with-mysqlclientlib
    --without-mysqlclientlib


Gem files will remain installed in /home/user/.rvm/gems/ruby-1.9.2-head/gems/mysql2-0.3.7 for inspection.
Results logged to /home/user/.rvm/gems/ruby-1.9.2-head/gems/mysql2-0.3.7/ext/mysql2/gem_make.out
An error occured while installing mysql2 (0.3.7), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.3.7'` succeeds before bundling.

Fix:

sudo apt-get install libmysqlclient-dev

rvm 1.9.2-head gem install mysql2

Monday, February 20, 2012

Sunspot issue - You need a Java Runtime Environment to run the Solr server

C:\Users\project1>rake sunspot:solr:run --trace
DEPRECATED! (configure_from_yaml) Please stop using YAML and use Ruby instead. T
his method will be removed in 2.9.
** Invoke sunspot:solr:run (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute sunspot:solr:run
The syntax of the command is incorrect.
rake aborted!
You need a Java Runtime Environment to run the Solr server

Fix:
Modify C:\Ruby192\lib\ruby\gems\1.9.1\gems\sunspot_solr-1.3.0\lib\sunspot\solr\java.rb file with

module Sunspot
  module Solr
    module Java
      def self.installed?
          true
      end
    end
  end
end

Also make sure your gemfile has:

gem 'sunspot_rails'
# This is an optional packaged Solr:
group :test, :development do
  gem 'sunspot_solr'
end

Reference Links:
https://github.com/sunspot/sunspot/issues/147

Monday, February 13, 2012

Useful links to install redis on windows

Download and install:
https://github.com/rgl/redis/downloads
References:
https://github.com/dmajkic/redis http://redis.io/documentation
You may need this as well:
http://www.mingw.org/wiki/Getting_Started http://sourceforge.net/projects/mingw/files/Installer/mingw-get-inst/mingw-get-inst-20111118/

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.