Thursday, July 10, 2014

Ruby exclamation mark method

In ruby, we see the methods with name ends with ?, ! Most of us know about the use of method name ends with ?. Ex: is_public? We are expecting the method to return result in boolean value(true/false). In exclamatory methods, usage is something different. See the following examples,
a = "A STRING"
puts a.downcase => a string
puts a => A String

puts b.downcase! => another string
puts b => another string
For no match case, gsub will return the actual string without any change in it
puts "ruby on rails".gsub("none","--") => ruby on rails
For no match case, gsub! will return nil
puts "ruby on rails".gsub!("none","--").inspect
People call methods ends with exclamation mark is dangerous to use/careful when using it. The reason is, in some cases it will throw exception instead of false. Ex:
save => return false if save fails
save! => raise an exception if save fails
We have a lot of exclamation mark methods in ruby, start looking on each one with their usage and start using it.
Hope it helps..

Tuesday, July 8, 2014

Rails try method name in object

In rails, most cases we are using the following style of code to display name, text etc..
user &&
It will go lengthier & is hard to maintain, check the below one
user && !user.comments.blank? && user.comments.first.text
Avoid lengthy expressions, start using "try"
It will return user name only if user object exists. Happy coding..

Monday, July 16, 2012

Modules in Ruby - an overview

We can define any number of methods in a module. It simply holds all the defined methods and we can include/extend it in any class.
If you want to use all module methods access by an instance then include the module in that class.
If you want to use all module methods access by an class then extend the module in that class.
module Foo
  def foo
    puts 'foo called!'

class Bar
  include Foo
end # foo called! # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end # foo called! # NoMethodError: undefined method ‘foo’ for #

Hope this helps. Happy learning & coding :)

Tuesday, February 28, 2012

Rails 3.1.0 - functional/integration test to test AJAX

Integration test with ajax achieved by means of calling xhr like below
xhr :req_method, :path, :parameters, :headers

xhr :get, '/users/new' # new user action

xhr :delete, '/users/20' # delete user

In integration test, you need to specify full path to make it work.

Incase of Functional test, we can simply specify the name of action.


Authlogic login access in rails functional test

We are shifted to use Authlogic, Devise rather than rails authorization plugin/gem. We can do Integration with detailed explanations/tutorials available for Authlogic.

In Rails test (functional/integration test in particular), we are in need to test whether the user is logged-in or not.
To start testing the user session, we need to use authlogic session. By using the following steps we can access Authlogic session in our rails test

- Add the following line in your test_helper.rb
require "authlogic/test_case"

- And add the method in your test_helper.rb
def user_login(user)
UserSession.create(user ? user : nil)

- Then inside your functional/integration test file
Add this to top of all test
setup :activate_authlogic

- Logged in with any existing user

You are logged in.
- User session is accessible.

Web application testing is much easier in Rails :)


Run ruby script as a background process in windows

Hi Ruby folks,

I went across a scenario in need of running a ruby process in background particularly in Windows OS(in Unix based system we can use '&' to run any process/job in background).

To run any ruby program in background, do the following

- Take a copy of the file, which you needs to run.
- Save the file as .rbw extension.
- Use the command
start "Your job description" ruby D:\Ruby\Jobs\particular_job.rbw

- Once it started running, You got a new console window with the given message on top and process status in console.


Thursday, October 20, 2011


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://

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"
n ='localhost', SOLR_PORT)

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

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

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]

– specified fields are indexed
We can specify the name of the fields to be used for searching.
: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

query => query is a string representing your query

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

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 = { |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|}

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