Installing raspell gem with bundler on mac os x

If you are using bundler to manage gems in your rails application and need to install a gem which requires special flags to be made available for proper installation of that gem, you can use the bundle config command alongwith the the flags that need to be set.

bundle config build.raspell --with-opt-dir=/opt/local
bundle install

You can then run the bundle install command to install the gem smoothly.

Undefined symbol: xsltLibxmlVersion – Ruby XSLT and CentOS

If you are facing the following error on your CentOS server:

require 'xml/xslt'
LoadError: /usr/lib/ruby/gems/1.8/gems/ruby-xslt-0.9.6/lib/xml/xslt_lib.so: undefined symbol: xsltLibxmlVersion - /usr/lib/ruby/gems/1.8/gems/ruby-xslt-0.9.6/lib/xml/xslt_lib.so
	from /usr/lib/ruby/gems/1.8/gems/ruby-xslt-0.9.6/lib/xml/xslt_lib.so
	from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
	from /usr/lib/ruby/gems/1.8/gems/ruby-xslt-0.9.6/lib/xml/xslt.rb:19
	from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
	from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
	from (irb):1

Try reinstalling the following packages and gems:

yum reinstall -y libxml2 libxml2-devel libxslt libxslt-devel
ldconfig
gem uninstall libxml-ruby ruby-xslt
gem install libxml-ruby ruby-xslt

Don’t forget to run ldconfig command as root user. This command creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line. More details on the command can be found here.

Running delayed delta daemon in background for thinking sphinx

Thinking Sphinx is a rubygem which provides excellent search capabilities within your rails application. Unlike other search mechanism like acts_as_solr, thinking sphinx has one major limitation, entries do not automatically get indexed when a new record is created or an existing record is updated. To overcome this limitation, thinking sphinx has support for delta indexes. These delta indexes either need to be merged with your main index or you need to run a process which automatically does this for you.

I have been trying to use one of the recommended advanced delta approaches, delayed deltas. If you are using this approach, you need to invoke the following command which automatically indexes new/updated entries and merges them into main index:

rake thinking_sphinx:delayed_delta
rake ts:dd # shortcut for above task

I found out that you cannot force the task to run in background and hence it is not suitable for production environment. This works well when you use it in development environment where you can debug code and see the task working.

You can use the following script to invoke a background process which essentially does the same work and can be used on the production server as well:

#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))

daemon_options = {
  :multiple => false,
  :dir_mode => :normal,
  :dir => File.join(dir, 'tmp', 'pids'),
  :backtrace => true
}

Daemons.run_proc('job_runner', daemon_options) do
  if ARGV.include?('--')
    ARGV.slice! 0..ARGV.index('--')
  else
    ARGV.clear
  end

  Dir.chdir dir
  RAILS_ENV = ARGV.first || ENV['RAILS_ENV'] || 'development'
  require File.join('config', 'environment')

  Delayed::Worker.new(
    :min_priority => ENV['MIN_PRIORITY'],
    :max_priority => ENV['MAX_PRIORITY']
  ).start
end

Just put this code into script directory of your rails application with filename delayed_delta and assign executable permissions. Now, you can use the following task to manage the background process on server:

ruby script/delayed_delta start RAILS_ENV=production  # Starts delta indexing daemon
ruby script/delayed_delta stop RAILS_ENV=production   # Stops delta indexing daemon
ruby script/delayed_delta status RAILS_ENV=production # Shows process id if the process is running
# => job_runner: running [pid 6200]

You can edit you capistrano deploy script to restart the daemon if required by adding th following code:

namespace :delayed_delta do
  desc "Start delayed_delta daemon."
  task :start, :roles => :app do
    run "cd #{current_path} && RAILS_ENV=production script/delayed_delta start"
  end

  desc "Stop delayed_delta daemon."
  task :stop, :roles => :app do
    run "cd #{current_path} && RAILS_ENV=production script/delayed_delta stop"
  end

  desc "Restart delayed_delta daemon."
  task :restart, :roles => :app do
    run "cd #{current_path} && RAILS_ENV=production script/delayed_delta restart"
  end

  desc "Show delayed_delta daemon status."
  task :status, :roles => :app do
    run "cd #{current_path} && RAILS_ENV=production script/delayed_delta status"
  end
end

after  "deploy:restart",     "delayed_delta:restart"

Hope this post saves your time.

Integrating Yahoo! BOSS with your rails application

What is Yahoo! BOSS? Yahoo developer website cites it as:

“Yahoo! Search BOSS (Build your Own Search Service) is an initiative in Yahoo! Search to open up Yahoo!’s search infrastructure and enable third parties to build revolutionary search products leveraging their own data, content, technology, social graph, or other assets. This release includes Web, News, and Image Search as well as Spelling Suggestions.”

Some of the possible implementation of Yahoo! Boss may be finding related posts for your article, suggested tag/category for an article/query, correcting misspelled words by providing suggestions, fetching latest news on a topic dynamically, search over delicious tags, customized language search. Some of these have been tried and successfully implemented. An example is the TechCrunch’s Search Engine.

Here is a concise guide on how to use this new service in your next rails application.

Obtain API key

Get an application key from http://developer.yahoo.com/search/boss/.

Install BOSSMan Gem

BOSSMan is a gem for interaction with the Yahoo BOSS web service written by John Pignata. Install it using the following commands:

gem install gemcutter
gem tumble
gem install bossman

Usage

Put this in your environment.rb

require 'bossman'
include BOSSMan
BOSSMan.application_id = <Your Application ID>

Web Search

Use the following code to execute search over the web:

boss = Search.web("Apple Pie", { :count => 2, :filter => "-hate" })
puts "Number of results: #{boss.totalhits}"

boss.results.each do |result|
  puts "#{result.title}"
  puts "#{result.dispurl}"
  puts "#{result.abstract}"
end

# => Number of results: 2618888
# => <b>Apple</b> <b>pie</b> - Wikipedia, the free encyclopedia
# => <b>en.wikipedia.org</b>/wiki/<wbr><b>Apple</b>_<b>pie</b>
# => English <b>apple</b> <b>pie</b> recipes go back to the time of Chaucer. <b>...</b> The basis of Dutch <b>apple</b> <b>pie</b> is a crust on the bottom and around the edges. <b>...</b>


boss = Search.web("Moon", { :count => 10, :type => "nonhtml,-pdf" })

boss.results.each do |result|
  puts "#{result.title}"
  puts "#{result.dispurl}"
  puts "#{result.abstract}"
end

# => BACKGROUND:
# => www.<b>radford.edu</b>/~rusmart/<wbr><b>moon</b>.doc
# => We noticed was that one of the scan lines took longer to scan the <b>moon</b> then any other. This occurred toward the middle of the <b>moon</b>. <b>...</b>


boss = Search.web("Star", { :sites => "wwe.com", :style=>'raw' })
boss.results.each do |result|
  puts "#{result.title}"
  puts "#{result.dispurl}"
  puts "#{result.abstract}"
end

# => John Cena - WWE: Raw
# => www.<b>wwe.com</b>/super<b>star</b>s/raw/<wbr>johncena
# => Official profile from WWE for the professional wrestler John Cena, who has been training since he was 15. Features lots of photos and video clips, including John ...

Apart from universal arguments mentioned at the end of this document, the following arguments can also be used:

Parameters Values/Description
:filter Filter out adult or hate content
Syntax: :filter => "-hate, -porn"
:type Specifies document formats (pdf, msoffice,etc)
:view Syntax: :view => "view1,view2", etc

:view => "keyterms" will retrieve related words and phrases for each search result.

:view => "searchmonkey_feed" will retrieve structured data markup, if available, for the search result in dataRSS format.

:view => "searchmonkey_rdf" will retrieve structured data markup, if available, for the search result in rdf format.

:view => "delicious_toptags" will retrieve the top public delicious tags for a document and the counts associated with each tag

:view => "delicious_saves" will retrieve the number of times a document was saved in delicious

:view => "language" identifies the language of the document

:abstract :abstract => "long" will retrieve and display an abstract of a web document up to 300 characters. This expanded abstract provides the requestor with a larger piece of information to work from in a web search query. The default for abstract is an abbreviated description.

Click here to view list of response fields returned by web search.

Images Search

For searching images on web, use the following code:

boss = Search.images("snow hills", { :dimensions => "large" })

boss.results.each do |result|
  puts "#{result.url}: #{result.abstract}"
end

# => http://www.amanita-photolibrary.co.uk/photo_library/BI_habitats/gb96_chiltern_hills_from_ivinghoe_snow_std.jpg: Copyright © 2004 Chiltern hills east from near Ivinghoe snow habitats landscapes British Isles

Click here for list of additional arguments that can be provided with image search.

Click here to view list of response fields returned by image search.

News Search

Yahoo! BOSS also provides news search capabilties.

boss = BOSSMan::Search.news("free shipping", { :age => "1d-2w", :o rderby => "date", :count => 1})

boss.results.each do |result|
  puts "#{result.title} [from #{result.source}]"
  puts "#{result.abstract}"
end
# => Wal-Mart announces weekly price cuts for holidays [from USA Today]
# => Wal-Mart said it will cut prices this holiday season for a week at a time on thousands of items, from bananas to board games. The first group of cuts hit Wednesday.

Click here for list of additional arguments that can be provided with news search.

Click here to view list of response fields returned by news search.

Spelling Search

Correct your misspelled words using its spelling suggestion feature:

boss = BOSSMan::Search.spelling("acknowlegment")
puts boss.suggestion # => acknowledgment

Site Explorer

You can also search for the pages from other sites linking into your site pages.

links = Search.se_inlink("http://mail.yahoo.com", :count => 2)
links.results.map { |result| p result.url }
# => http://www.aol.com/
# => http://groups.yahoo.com/

For displays a list of all pages belonging to a domain in the Yahoo! index, use se_pagedata method provided.

links = Search.se_pagedata("twitter.com", :count => 1)
links.results.map { |result| p "#{result.url} - #{result.abstract}" }
# => http://twitter.com/ - Use Twitter to send status updates (tweets) through your cell phone, instant messenger, or via the Web, and notify friends and followers of the little things <b>...</b>

Universal Arguments for Web, Images and News

Following is the list of most commonly used arguments with web, image and news search. For more comprehensive list click here

Argument Options/Details
:start Ordinal position of first result. First position is 0. Default sets start to 0.
:count Total number of results to return. Maximum value is 50. Default sets count to 10.
:format The data format of the response. Value can be set to either "xml" or "json". Default sets format to "json".
:callback The name of the callback function to wrap the result. Parameter is valid only if format is set to "json". No default value exists.
:sites Restrict BOSS search results to a set of pre-defined sites. Multiple sites must be comma separated. Example: (:sites => "abc.com,cnn.com"). The Images service does not yet support multiple sites.
:view Retrieve additional search data provided by the respective BOSS service. Please see individual chapters to see what view options are available.
:style By default for web search result titles and abstracts contain bold HTML tags around the search term. Use :style => "raw" to remove the bold tags around the search terms in titles and abstracts.

Defining fixtures for table without model in rails

Few days back, I need to write rspec tests for one of my ongoing projects. I had a self referential association like this:

class User
  has_and_belongs_to_many :friends,
                        :class_name               => "User",
                        :join_table               => "friends_users",
                        :association_foreign_key  => "friend_id",
                        :foreign_key              => "user_id"
end

I had friends_users.yml file in my fixtures. Since I did not have any intermediate model, I could not use fixtures defined in users.yml in friends_users.yml. I was able to find a way out within Fixtures class itself. Here is the snippet from friends_users.yml

jack_and_jill:
  user_id: <%= Fixtures.identify('Jack') %>
  friend_id: <%= Fixtures.identify('Jill') %>

Here is snippet from users.yml:

Jack:
  name: Jack Brown
Jill:
  name: Jill Green

For further details, refer to rails api documentation here

Using calendar_select in DHTML Calendar plugin for rails

The DHTML / JavaScript Calendar is a javascript library for creating customized calendars. The library has been ported as a rails plugin, dhtml calendar.

Using calendar_select from this plugin, I found that the date time fields were not being updated after I picked up a date from date select popup. I had to modify lines 27-35 in calendar.rb from

if show_field == :select
  input_field_year_id = "#{object}[#{method}(1i)]"
  input_field_month_id = "#{object}[#{method}(2i)]"
  input_field_day_id = "#{object}[#{method}(3i)]"
  if calendar_options.has_key?(:showsTime) and calendar_options[:showsTime]
    input_field_hour_id = "#{object}[#{method}(4i)]"
    input_field_minute_id = "#{object}[#{method}(5i)]"
  end
end

to

if show_field == :select
  input_field_year_id = "#{object}_#{method}_1i"
  input_field_month_id = "#{object}_#{method}_2i"
  input_field_day_id = "#{object}_#{method}_3i"
  if calendar_options.has_key?(:showsTime) and calendar_options[:showsTime]
    input_field_hour_id = "#{object}_#{method}_4i"
    input_field_minute_id = "#{object}_#{method}_5i"
  end
end

The plugin internally uses datetime_select and date_select to create year select with DOM id as “#{object}_#{method}_1i” and DOM name as “#{object}[#{method}(1i)]“. The DOM name variable was been referenced in the calendar.rb which did not update the fields when user tries to pick a date from popup. On changing this to DOM id variable, everything worked fine.

Ruby Funday : A Day full of Ruby Fun

The first ruby full day event of its kind is to be held on 22nd November, 2008 at Impetus, Noida.

Here are the highlights of the day…

  • Flex on Rails
  • Internationalization Rails
  • FxRuby & ActiveRecord
  • Facebook App on Rails
  • Integrating Voice gateways in Rails
  • Soft Rock
Ruby Funday Logo

 

 

 

 

 

 

 

More details on event and venue can be found at rubyonrails.in

See you there.