Thursday, February 28, 2008

square brackets [] class method of Hash

[] class method of Hash converts an array into a hash.


irb(main):001:0> Hash["name","subbu","profession","programmer"]
=> {"name"=>"subbu", "profession"=>"programmer"}
irb(main):002:0> my_array = %w{ a b c d }
=> ["a", "b", "c", "d"]
irb(main):003:0> Hash[*my_array]
=> {"a"=>"b", "c"=>"d"}

Preventing sensitive data from being logged in Rails log file

filter_parameter_logging :password

References:
1. http://api.rubyonrails.org/classes/ActionController/Base.html#M000441
2. Page 610 of 'Agile Web Development with Rails'

Route Globbing

The default route "map.connect ':controller/:action/:id'" is sufficient in most of the cases when dealing with URLs and routing. It matches most of the common URLs that are coming your way. But what if we need an URL like:

www.mysite.com/2008/02/5/28/18/30/20 which might mean:
www.mysite.com/year/month/week/day/hour/minute/second

There is something called as Route Globbing to solve this problem. In your routes.rb file specify the following line:
map.connect 'year/month/*values'

Routing engine bundles all the values after the third slash into params[:values] as an array. So your year/month action will have access to this array. The params[:value] will now look like ["5","28","18","30","20"].

If we want another controller to receive the URL, then we can say:
map.connect 'year/month/*values', :controller => "accounts"


Route globbing could be helpful if we are allowing users to enter some kind of organizational structure or file paths in to the URL.

Monday, February 25, 2008

String: extract a single character

Whenever I wanted to extract a single character from a string, invariably I started with something like "hello"[1] and Ruby returns 104. That's the ascii code for 'h'. Its not at all useful. I should practice saying "hello"[0,1] which will return what I want, i.e. 'h'.

Thursday, February 21, 2008

require and load won't reload the file with reload! in rails console

I have the statement "require 'primary_user' " in one of my models of my Rails application. Usually whenever I do a 'reload!' in my rails console, it reloads all the models and their associates files so that any changes to code can be seen in the console. But there is a catch to that reload!. It doesn't reload any of the files loaded using the 'require' statement. So my 'primary_user' file wasn't getting reloaded. Strange. But that's how it works. I tried changing 'require' to 'load' but no use.

Tuesday, February 19, 2008

Rails without a database

Add this to environment.rb:
config.frameworks -= [ :active_record]


This is what lines 19 to 21 in environment.rb say (Rails version 2.0.2):
  # Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]

Sunday, February 17, 2008

eval

eval("foo", binding)
Evaluate string in the context of binding. In this case 'foo' is executed as code in the context of binding. The second parameter is optional. It could either be a proc object or a binding object. If the second parameter is missing then the scope is set to current.

class_eval
Evaluate the code inside the context of a class. Example:

Array.class_eval <<-addons
def total
self.inject do |s,e|
s+e
end
end
addons

a=[1,2,3,4]
puts a.total


We can say something like "Array.class_eval('some goes here')" and the code will be executed within the context of Array class.

module_eval
Same as class_eval

Here is an excellent article:
http://www.infoq.com/articles/eval-options-in-ruby

binding in ruby

This is what 'The Ruby Way' (Section 11.3.1) says about the 'binding':
You can encapsulate the current binding in an object using the method Kernel#binding. Having done that, you can pass the binding as the second parameter to eval, setting the execution context for the code being evaluated.

def some_ethod
a = "local variable"
return binding
end

the_binding = some_method
eval "a", the_binding # "local variable"


So, in an IRB session:

irb(main):001:0> a = "I am a local variable"
=> "I am a local variable"
irb(main):002:0> eval("a", binding)
=> "I am a local variable"
irb(main):003:0>


When we pass a block to the method, the binding preserves it.

def bindng
return binding
end

s = bindng{|v| puts v}
eval("yield('subbu')", s)


I don't know how this can be used though.

Another example that talks about binding with a nice context to use it:
http://railscasts.com/episodes/86

Friday, February 15, 2008

ActiveRecord tricks - :include and :select options

When I say something like:

Project.find(:all, {
:select => "projects.id, projects.name, tasks.id, tasks.owner",
:include => :tasks
})
The AR returns all fields from projects and tasks table. Whenever there is an :include option, it just ignores the :select options. To work around this, we can either specify the :join option like:

Project.find(:all, {
:select => "projects.id, projects.name, tasks.id, tasks.owner",
:join => "LEFT OUTER JOIN tasks ON projects.id = tasks.id WHERE projects.id = #{whatever}"
})

Or, we can specify the whole SQL like:
Project.find_by_sql("SELECT projects.id AS p_id, projects.name AS p_name, tasks.id AS t_id, tasks.owner AS t_owner
FROM projects LEFT OUTER JOIN tasks ON projects.id = tasks.id WHERE projects.id = #{whatever}")
We don't have to know a lot of SQL to write these work around solutions. Just look for the generated SQL query in the log file when you specified the :include option, copy that SQL, modify it and use it here.

Friday, February 8, 2008

Convert String to Range

class String
def to_range
case self.count('.')
when 2
elements = self.split('..')
return Range.new(elements[0].to_i, elements[1].to_i)
when 3
elements = self.split('...')
return Range.new(elements[0].to_i, elements[1].to_i-1)
else
raise ArgumentError.new("Couldn't convert to Range:
#{str}")
end
end
end

p "1..2".to_range
p "1...2".to_range
p "1.2".to_range

output:
1..2
1..1
rng.test:11:in `to_range': undefined local variable or method `str'
for "1.2":String (NameError)
from rng.test:18


http://www.ruby-forum.com/topic/141926#629921

Thursday, February 7, 2008

Prevent a class from instantiating

class Myclass
class << self
undef_method :new
end
end

Wednesday, February 6, 2008

SQL joins explained

While trying to understand various 'sql joins' I stumbled upon some nice articles. The only problem with them was they were scattered across places. I had to put them in a word document so that I can print and take them home for further reading. Here are those documents.
A Visual Explanation of SQL Joins
Assorted articles on SQL Query Joins.pdf


Note: None of the material in these documents is written by me. Click on the link in "Original article at:" in the document to visit the original article.