Thursday, October 20, 2011

Solr

Integrating SOLR search into our application. “acts_as_solr” is the name of the plugin(also available as gem).
Install plugin:
script/plugin install git://github.com/mattmatt/acts_as_solr.git

Install gem:
gem install acts_as_solr


Add the below line into your application's configuration file
config.gem "acts_as_solr"

Add this at the end of your Rakefile(only for using gem)
require 'aas_tasks'

After installing gem/plugin, following rake tasks are available to use
rake solr:destroy_index # Remove Solr index
rake solr:reindex # Reindexes data for all ac
ts_as_solr models.
rake solr:start # Starts Solr.
rake solr:stop # Stops Solr.
We can start, stop, reindex, destroy index by using the mentioned rake tasks.


Add the following rake task inside the solr rake file(gems/acts_as_solr/lib/tasks/solr.rake), to start solr in Windows environment.
desc "Starts Solr. on windows . Options accepted: RAILS_ENV=your_env, PORT=XX. Defaults to development if none."
task :start_win do
require "#{File.dirname(__FILE__)}/../../config/solr_environment.rb"
begin
n = Net::HTTP.new('localhost', SOLR_PORT)
n.request_head('/').value

rescue Net::HTTPServerException #responding
puts "Port #{SOLR_PORT} in use" and return

rescue Errno::ECONNREFUSED #not responding
Dir.chdir(SOLR_PATH) do
exec "java -Dsolr.data.dir=solr/data/#{ENV['RAILS_ENV']} -Djetty.port=#{SOLR_PORT} -jar start.jar"
sleep(5)
puts "#{ENV['RAILS_ENV']} Solr started sucessfuly on #{SOLR_PORT}, pid: #{pid}."
end
end
end



Steps to configure solr in our application

1) Starts the solr server
rake solr:start


2) Changes to ActiveRecord model
acts_as_solr - all fields are indexed
class News < ActiveRecord::Base
acts_as_solr :fields => [:title, :content]
end

– specified fields are indexed
We can specify the name of the fields to be used for searching.
Options:
:if => we can supply any condition as string, proc, symbol, method. It will index the record only if condition returns true.

3) Do index/reindex
rake solr:reindex


4) Changes to Controller
News.find_by_solr(query)

query => query is a string representing your query

There are many options available in solr, we can do a refined search by using SOLR.

Problem:
I faced one problem, acts_as_solr :if option is not working with rake task to reindex data. Instead of checking the condition it will simply indexes all the records. But other method like solr_save() checks the condition passed with acts_as_solr definition in model. I have added a patch to check the condition in rake task 'reindex'.

file path: acts_as_solr\lib\class_methods.rb
line no: 200 - 250
method name: rebuild_solr_index
Instead of normal collect,
items.collect! { |content| content.to_solr_doc }


We can use the following code, to filter the records with the condition defined in model and collect the remaining results
items = items.select { |content| content.evaluate_condition_public(content)}
items.collect! { |content| content.to_solr_doc }


After doing the above changes, you can have a correct data in your search results. This is applicable only when we are using acts_as_solr with conditions in model.

acts_as_solr :fields => ["name","description"], :if => proc{|record| record.active?}


Hope, this is useful for someone who is using acts_as_solr with :if option.

Cheers,
Vadivelan

Thursday, August 18, 2011

Functional Testing in Rails(to test Html)

Hi all,

I have used listed out some uses of assert_tag in Rails functional test. In many case, we need to test the html content of page like checkbox is checked or not, text fields holds correct value, drop down selected with correct option. For those kind of needs, we need to go for assert_tag. Below are the example usage of assert_tag in functional testing.

In Rails html testing, assert_tag method plays an vital role. Following are some of the ways to use assert_tag method


Get links inside div

assert_select "div#divID" do
assert_select "a[href=?]", "/path/to/some/page"
end

Check the content of any html element(here is an example for Div)

by className
assert_select "div.className", "Page Heading or content inside the div"
by element ID
assert_select "div#elementId", "Page Heading or content inside the div"

Check how many times any DOM element appears on the page:

In the below example, we tested how many number of user images loaded on the page
assert_select "div.className table tr td.userImage img", {:count => 4}

Presence of Textbox:

assert_tag "input", :attributes => {:id => "user_screen_name", :size => "30", :type => "text"}

Get value of Dropdown:

option = css_select("select#elementId option[selected='selected']")[0]
assert_equal "public", option['value'].to_s

Code with testcase improves the quality of code and at the sametime reduces the errors. Keep writing test for each line of code.

Monday, April 18, 2011

Alternative to "grep" command in Windows

Hi all,

I have shifted from ubuntu and started using windowsXP. When I tried to use the grep command in windows, it throws the error

Instead of using grep, we can use find
gem list|find "rails"

rails (3.0.10)

Cheers,
Vadivelan

Wednesday, February 2, 2011

Month with number of count display for any model in your application

By using rails finder method, it is very easy to display the number of post and month accordingly.
Here is the query

>> Post.count(:order => 'DATE(created_at) DESC', :group => ["DATE_FORMAT(created_at,'%m/%Y')"])
=> #< OrderedHash {"06/2010"=>1, "03/2010"=>1, "02/2010"=>1}>

Result is a collection hash ordered in the form of latest month as first one, Collection contains the month as Key and number of count as Value.

If we run it through the each loop and it is very easy to display.

Thanks,
Vadivelan

Monday, January 10, 2011

Ruby keywords

List of ruby keywords

1. alias
2. and
3. BEGIN
4. begin
5. break
6. case
7. class
8. def
9. defined
10. do
11. else
12. elsif
13. END
14. end
15. ensure
16. false
17. for
18. if
19. in
20. module
21. next
22. nil
23. not
24. or
25. redo
26. rescue
27. retry
28. return
29. self
30. super
31. then
32. true
33. undef
34. unless
35. until
36. when
37. while
38. yield

Sunday, January 9, 2011

SQL order_by "field" option

Hi all,

I tried to order the SQL results in a pre-defined order. Consider the case

Am having users table, and a field called 'status' to store the current status of the user.
In back-end of my site, am displaying all the users with order-by 'status'

Possible status values are "Pending", "Approved", "Canceled", "Deleted"

I need to display users in the following orders,
"Approved", "Pending", "Canceled", "Deleted"

The normal order by field orders the field in either ASC/DESC. But in this case it is different.
For this i used the following query to fetch SQL results in a defined order

Rails finder:
User.find_by_sql("select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted')")

SQL query:
select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted');

Result contains the collection in the defined order.

When you are using this "order by field" option, you have to give all the option in the order then only it will works.

Thanks,
Vadivelan