Translate

February 5, 2014

What is the difference between Symbol and String in Ruby?

The symbol in Ruby on rails act the same way as the string but the difference is in their behaviors that are opposite to each other.

The difference remains in the object_id, memory and process time for both of them when used together at one time.

Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable.

Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten.

String objects are written like
irb(main):001:0> "string object apple".object_id #=>70278982314860
or
irb(main):002:0> "string object
apple".to_sym.object_id #=> 456148

Symbols are used to show the values for the actions like equality or non-equality to test the symbols faster then the string values.

January 14, 2014

Difference between Argument and Parameter in ruby on rails?

A parameter represents a value that the method expects you to pass when you call it.
An argument represents the value you pass to a method parameter when you call the method. The calling code supplies the arguments when it calls the method.

In simple words, parameters appear in method definitions; arguments appear in method calls.

For example, in below method, variables param1 and param2 are the parameters

def foo_method(param1, param2):
    .......
end

while calling the method, arg1 and arg2 are the arguments
 
foo_method(arg1, arg2)

January 9, 2014

What are filters? and how many types of filters are there in ruby?

Filters are methods that are run before, after or "around" a controller action.

Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.

Filter can take one of three forms: method reference (symbol), external class, or inline method (proc).

          after_filter
    append_after_filter
    append_around_filter
    append_before_filter
    around_filter
    before_filter
    filter_chain
    prepend_after_filter
    prepend_around_filter
    prepend_before_filter
    skip_after_filter
    skip_before_filter
    skip_filter

December 18, 2013

What is the difference between save and save! in Rails?

Save! performs all validations and callbacks. If any validation returns false, save! throws an error and cancels the save.

Save does not throw any error in the case above, but cancels the save. Also, the methods for validations can be bypassed.

October 16, 2013

What is the difference between delete and destroy in Rails?

The delete method essentially deletes a row (or an array of rows) from the database.
Destroy on the other hand allows for a few more options. First, it will check any callbacks such as before_delete, or any dependencies that we specify in our model. Next, it will keep the object that just got deleted in memory, this allows us to leave a message saying something like “ 'Object_name' has been deleted.” Lastly, and most importantly, it will also delete any child objects associated with that object!

September 24, 2013

Case equality operator === in ruby

To enable developers to write neat, compact code, Many classes take advantage of implementing their own versions of '==='. The '===’ operator is known as the case equality operator. The '===’ operator is used when testing cases in case statements.
def test_object number 
  case number
    when Fixnum
      case number 
        when 1  
          puts "It's One"
        when 2..10  
          puts "Between two and ten"
        else
          puts "-- #{number} -- is not between one and ten"
      end
    when String 
      puts "You passed a string"
    else "I have no idea what to do with -- #{number} --"
  end
end
for each 'when' statement the '===' operator is called on the when argument (1,2..10,String) and the case argument (number) is used for the comparison. For line 5 the comparison done shall be '1 === number'. For most classes ‘===’ is just an alias to ‘==’ however some classes redefine ‘===’ to allow for better functionality in case statements. In Ruby a Proc is a block of executable code, an anonymous function which can be passed around as if it were data. Like ‘===’, a Proc can map a number of arguments to either a true or false value.
is_weekday = lambda {|day_of_week, time| time.wday == day_of_week}.curry  
      
    sunday    = is_weekday[0]  
    monday    = is_weekday[1]  
    tuesday   = is_weekday[2]  
    wednesday = is_weekday[3]  
    thursday  = is_weekday[4]  
    friday    = is_weekday[5]  
    saturday  = is_weekday[6]  
      
    case Time.now  
    when sunday   
      puts "Day of rest"  
    when monday, tuesday, wednesday, thursday, friday  
      puts "Work"  
    when saturday  
      puts "Happy"  
    end  
Simple Factorial lambda function in Ruby
factorial = lambda do |n|
  n <= 1 ? 1 : (n * factorial.call(n - 1))
end

factorial.call 3

July 24, 2013

SQL Injection in rails

How to avoid SQL Injection in rails

How to avoid SQL Injection in rails

SQL injection is a problem that every web developer needs to be aware of when accepting parameters that will during the life of the request be converted into SQL statements. Rails historically has done what it can to mitigate this risk for the developer by providing vehicles for sanitizing parameter inputs at the points when they are being converted for use inside of a SQL statement, however with Rails 3 there are numerous ways to execute a SQL statement against the database and some of these methods are safer than others.
Consider two cases where valid Rails code is vulnerable to SQL injection:

user inputed parameters

params[:query] = "'username'; DROP TABLE EMPLOYEE;"

CASE 1 - find_by_sql

User.find_by_sql("SELECT * FROM users WHERE (name = '#{params[:query]}'")

(Not Good)

generated SQL

SELECT users.* FROM users WHERE (email = 'user@example.com'); DROP TABLE EMPLOYEE; ')
(THIS STATEMENT WILL DROP TABLE EMPLOYEE)
The example above shows how find_by_sql can allow parameters submitted by a user to be directly entered into a SQL statement and how an attacker might use the vulnerability to wreak havoc. These types of find_by_sql statements used to be more commonly used in earlier versions of Rails (1.0 - 2.0) and it was through these statements that the Rails community realized that SQL injection was a problem that needed addressing. Here's another example prominent in the early Rails days:
User.find :first, :conditions => "(name = '#{params[:query]}')" ##(BAD BAD BAD) produces this SQL statement:

generated SQL

SELECT users.* FROM users WHERE (email = 'user@example.com'); DROP TABLE EMPLOYEE;')
(THIS STATEMENT WILL DROP TABLE EMPLOYEE)
The above example shows a common Rails idiom for performing an ActiveRecord query, as with the previous find_by_sql example the find query here is piping the param in directly and generating the exact same tainted SQL.
Fortunately, Rails core decided to make it easier to just do the right thing and provided ways to pass in parameters by using built-in filters that handle special SQL characters, which will escape ’ , " , NULL character and line breaks. Instead of passing in the parameter directly as a raw string, you can pass in an array to sanitize the tainted strings using the built-in filters:
User.find_by_sql(["SELECT * FROM users WHERE (name = ?)", params])
(GOOD)
User.find :first, :conditions => ["(name = '?')", params]
(GOOD)

generated SQL

SELECT * FROM users WHERE (name = 'user\'); DROP TABLE EMPLOYEE; ') (RETURNS NIL)
The distinction in the filtered SQL statement is the escaped single quote right after the t in Robert which prevents the name parameter from terminating and allowing the DROP TABLE EMPLOYEE from being executed since it remains a part of the string parameter. Additionally, Rails also included these built-in filters automatically when AR queries were called from find_by_something or a conditions hash:
User.find_by_name(params[:query])

(GOOD)

generated SQL

SELECT * FROM users WHERE users.name = 'username\'); DROP TABLE EMPLOYEE; ' (RETURNS NIL) User.find :first, :conditions => {:name => params}

(GOOD)

SELECT users.* FROM users WHERE users.name = 'username\'); DROP TABLE EMPLOYEE;' (RETURNS NIL)
Rails 3 introduced AREL, which is another way to perform ActiveRecord queries and with it came as well, another way to make the exact same SQL injection mistakes that are already listed above. However having gotten accustomed to looking for SQL injection vulnerabilities in the AR query formats above you might be lulled into thinking that the new and improved ActiveRecord query methods would just magically handle the tainted strings for you and you'd be dead wrong:
User.where("name = '#{params}'") (BAD) SELECT users.* FROM users WHERE (name = 'username'); DROP TABLE EMPLOYEE; ##') ##(THIS STATEMENT WILL DROP TABLE EMPLOYEE)
The nice thing is that the same fix can also be applied:
User.where(["name = ?", params]) SELECT users.* FROM users WHERE (name = ''username\'); DROP TABLE EMPLOYEE;
(RETURNS NIL)