Thursday, May 31, 2012

Making a clear concept on passing &block

If we want to pass simple arguments we can use simply

def my_function(*args)
end

But if we want to pass a block of code to the function, at that time we need &block. We can pass &block simply as:

def my_function(args, &block)
  #here args are arguments
  #&block is the block of code we have passed through
end

i.e my_function(["a","b","c"], block_of_code )
An example illustrating the best scenerio:

def variable(&block)
  puts ‘Here goes:’

  case block.arity
  when 0
    yield
  when 1
    yield ‘one’
  when 2
    yield ‘one’, ‘two’
  when 3
    yield ‘one’, ‘two’, ‘three’
end

puts ‘Done!’

end

We’re declaring block as a method parameter here so we’ll have more access to it. The ampersand in front indicates that it’s going to be take the code block and put it into the Proc object block. Once we’ve got block we can see how many parameters it takes (Proc#arity) and deal with it accordingly. So how does that work?

variable {} »

Here goes:
Done!


variable { |x| puts x } »

Here goes:
one
Done!


variable { |x,y| puts x, y } »


Here goes:
one
two
Done!


variable { |x,y,z| puts x, y, z } »

Here goes:
one
two
three
Done!

Wednesday, May 30, 2012

Extract file type in ruby.


You can simply find the file type of a file where file.content_type doesnot  works

options[:form] = "./lib/cf/cli/templates/sample-line/form.html"
file_type = IO.popen(["file", "--brief", "--mime-type", options[:form]], in: :close, err: :close).read.chomp

The return type is simply  "text/html"

Tuesday, May 29, 2012

How to deploy code to heroku?


Following are the steps you should have to follow while creating a new app to deploy your codes to the heroku.
rails new checkonce
cd checkonce
git init
git add .
git commit -m"init"
heroku login
gem install heroku
heroku create
heroku create checkonce
heroku keys:add ~/.ssh/id_rsa.pub #if Permission denied (publickey)
git push heroku master

Sunday, May 27, 2012

Rspec asserting array regardless of orders

Sometimes when we want to make assertion of array in  our rspec  then assertion gets failes which in result make the spec failure.
nums = [1,2,3].shuffle
nums.length.should == 3
nums.should include 1
nums.should include 2
nums.should include 3
If we can prevent this buy using =~ opreator where we want to assert in our spec.
[1,2,3].shuffle.should =~ [1,2,3]