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


b = "ANOTHER 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 && user.name
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"
user.try(:name)
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!'
  end
end

class Bar
  include Foo
end

Bar.new.foo # foo called!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class

class Baz
  extend Foo
end

Baz.foo # foo called!
Baz.new.foo # 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.

Cheers,
Vadivelan.K

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)
end

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

- Logged in with any existing user
user_login(users(:last))

You are logged in.
- User session is accessible.

Web application testing is much easier in Rails :)

Cheers,
Vadivelan.K

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.

Cheers,
Vadivelan.K

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

Wednesday, November 10, 2010

ActiveRecord::Base increment & decrement method

Hi all,

Yesterday while i was working in a task, i need to increase the points of an user. For that i have used the update_attribute method like below

user = User.last
user.update_attribute(:points, 5)

Then i found the active record base in-built method called "increment" and "decrement". So i used the following method to increment/decrement the user points.

user.increment(:points) # it will increase points by 1(default increment count) and returns the user object(self)
user.save
user.increment!(:points) # and this one will do the above two operations i.e., assigns the value to the attribute and saves the record. It will returns true or false(validation result).

user.increment(:points, 5) # we can pass the value like this to increment the attribute by this much. Here points will increases by 5
user.save
user.increment!(:points, 5)

The same is applicable to the "decrement" method, syntax is given below
user.decrement(:points)
user.decrement!(:points)
user.decrement(:points, 5)
user.decrement!(:points, 5)


Thanks,
Vadivelan

Wednesday, October 6, 2010

Use of rails console

Hi all,

We can use our rails console(powerful tool for rails app) for debugging and testing. Mainly console helps us to learn more about Ruby

Normally we are using console to talk with our database, and fetch the objects from db.
ex:
User.first
User.all

But apart from that we can use our console to interact with our application using the object "app"
"app"

app.class # returns this
ActionController::Integration::Session

we can fire(get/post) requests to our application from console itself.

>> app.get "/login"
=> 200
it returns the status code for the handled request

>> app.post "/user_sessions", :user_session => {:email => 'vadivelan@example.com', :password => 'secret'}
=> 302
we can send post request with parameters like this

>> app.response.redirect?
=> true
redirected to some other url

>> app.response.redirect_url
=> "http://localhost/login"
view the redirect url

Hope now you guys can start firing the requests to application from console.

Thanks,
Vadivelan

Friday, September 24, 2010

ruby send method

Hi all

I am started using the method named "send".

We can use this to call the method using object.

class User

def say_hello
"Hello"
end

end

u = User.new
puts u.send(:say_hello)

Here the class "User" is having the method called say_hello. We can create an object for the user class and call the method using the method "send"

Cheers,
vadivelan

Tuesday, September 21, 2010

ruby extend method

Hi all,

I have seen the method named "extend" used in a line of code in Plugin. Then i started searching for the use of method "extend". And i found the following

consider the example

module Friend
def say_hello
"hello am inside module"
end
end

class Person
def say_hello
"hello am inside class"
end
end

p = Person.new
puts p.say_hello #=> hello am inside class

p.extend(Friend) #=> include all the instance method from Module "Friend"
puts p.say_hello #=> hello am inside module


So the extend method is used to include the Module.
Without this we cannot call the method inside the module using the Person object. Even if i added include the module in the class, it wont calls the module method. The instance method inside the class gets called for the object(Person class).

Wednesday, September 15, 2010

Use of Proc & proc

Hi

I have used "proc" to run/block validation in model. But now i learned something more about proc.
In ruby, "Proc"(procedure) refers to the block of code, we can reuse it. Block of code assigned to the object.

"Proc" => Starts with capital letter refers to (class name)
"proc" => Refers to the proc object

We can use both the keywords to create a proc by defining any block to them.

below sample code to create a proc and call that proc to execute the block of code

accepts_any_arg = Proc.new{ |a,b,c|
puts "#{a} #{b} #{c}"
}
accepts_any_arg.call(1)
result: 1
accepts_any_arg.call(1,2)
result: 1 2
It just neglects the number of arguments required or passing to that proc, it is working without any argument error. It assigns nil value to arguments which are not passed.


throws_args_error = proc{ |a,b,c|
puts "#{a} #{b} #{c}"
}
throws_args_error.call(1,2,3)
result: 1 2 3
throws_args_error.call(1)
result: Throws "ArgumentError"
it is checking the number of arguments


Thanks,
Vadivelan

Thursday, July 22, 2010

Ruby - "defined?" method

Hi all,

In ruby we are having many methods to check whether the variable defined or not. Mostly we are using the following condition to check the variable defined or not

Code:
if local_variable
puts "local variable exists"
else
puts "local_variable does not exists"
end

But there is another way to check the variable defined or not.

sample-code:

a = 10
puts defined?(a).inspect => "local-variable"
puts defined?(b).inspect => nil

So, the method returns the value "local-variable" for the already defined variables and "nil" for the undefined variables.

Hope hereafter you guys using the method "defined?" to check the variable already defined or not.

Cheers,
Vadivelan

Monday, May 24, 2010

ruby math functions

Hi all,

Here i have listed some of the most frequently used math functions in ruby.

round method rounds the value
if decimal value is less than .5, rounded to its lowest value
irb(main):006:0> 1.2.round
=> 1
if decimal value is greater than .4, rounded to its highest value
irb(main):007:0> 1.5.round
=> 2

floor method rounded the value to lowest value
irb(main):008:0> 1.5.floor
=> 1

ceil method rounded the value to next highest value
irb(main):009:0> 1.5.ceil
=> 2

'nan' method used to check whether the value is integer or not
irb(main):010:0> x = 0.0/0.0
=> NaN

irb(main):011:0> x.nan?
=> true

Get ASCII value
irb(main):017:0> Integer(?e)
=> 101

irb(main):018:0> Float(?e)
=> 101.0

>> "%.2f" % (1.0/2.0)
=> "0.50"

The last method is mainly used for display purpose. We have to display the floating point number in any page(say to display the cost) we must modify the output in such a way to get clear display(Max of 2 numbers after decimal point in this case).


Thanks,
Vadivelan

Some more uses of '$' in prototype javascript

Hi all,

We are all using the '$' in prototype javascript to get the object of the matched DOM element by using id of the element.

Say for example:

the page has the div element

content inside the div element


To get the object of the div element we are using the '$'.

$('container') => returns the object of the DOM element.

$A/$W/$F => are also available but rarely used..

the below lines explain the use of the $A/$W/$F

// converts a string into array, each element is taken as a count
>>> $A('1')
['1']
>>> $A('123')
["1", "2", "3"]

// converts a string into array, it takes whitespace as delimiters
>>> $w('1 2 3')
["1", "2", "3"]

// used to get values of text field which is located inside any forms
// same as Form.Element.getValue
>>> $F('press_room_url')

So start using these commands makes the code simpler..


Thanks,
Vadivelan