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

Wednesday, March 31, 2010

jQuery with rails

Hi all,

I have used the jquery js prototype recently, it has lots of more usage than our prototype.js. Easy to code using jQuery.js.

But in my rails application i have used both prototype.js & jquery.js. In this situation the $ gets conflict. To avoid conflict, use the line of code

First include prototype.js, then add jQuery.js after that you must add this line to avoid ($)conflict


Once you done this, you can enjoy the usage of both prototype.js & jQuery.js.

i.e., both $ and $j is available to access.

$('id_of_dom_elemnt') => returns (prototype)object of the html element
$j('#id_of_dom_element') => return (jquery)object of the html element

In jQuery, we have to add '#' symbol with id of dom element to find the element.

Enjoy coding with jQuery...

thanks,

Saturday, January 23, 2010

JSON startup

JSON - javascript object notation

To know about the JSON, first go through the following basics in js.

Array:

var arr = new Array("first", "second", "third", "fourth");

Retrieve value from array

arr[0] => "first"
arr[1] => "second"


Object:

var sample_object = {
"name1" : "value1",
"name2" : "value2",
"name3" : "value3",
"name4" : "value4"
}

sample_object.name1 => "value1"
sample_object["name1"] => "value1"



Objects in Array

var object_array = [
{
"first_element" : "first_value"
},
{
"second_element" : "second_value"
}
]
object_array[0] => returns first object
object_array[1].second_element => second object value


Arrays in Object:

var sample_object = {
"name1" : "value1",
"name4" : [1,2,3,4]
}
sample_object.name4 => [1,2,3,4]
sample_object.name4[0] => 1

var str_json = JSON.stringify(sample_object);
var js_object = JSON.parse(str_json);
JSON.parse(strJSON) - converts a JSON string into a JavaScript object.
JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.