Thursday 2 July 2015

Some Ruby Thing

The following post consist of some features in ruby that are lesser known to people.

1. alias for '.call'

class Ticket
  def purchase
    puts "** Purchasing the Ticket **"
  end 
  alias_method :call,:purchase
end

## Following are they way you can invoke the download method
Ticket.new.purchase
## => ** Purchasing the Ticket **
A.new.call
## => ** Purchasing the Ticket **
A.new.()
## => ** Purchasing the Ticket **

2.  Disabling (SSL) Certificate Check from all Gems or Ruby Libraries.

unless Rails.env.production?
  class Net::HTTP
    def verify_mode=(verify_mode)
      @verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end  

Note:

  • Do this only on your local or development environment.
  • Also the above code only work if the libraries or gem uses 'Net::HTTP' API internally, 
  • Tested with HTTParty,Faraday,RestClient not working with Excon(so Excon adapter over Faraday might not work as well).




3. Locking a file using flock.
    Firstly I advise you to read through flock and also this amazing answer by Arjun Shankar.
 
flock (locking_constant )→ 0 or falseclick to toggle source
Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.
Locking constants (in class File):
LOCK_EX   | Exclusive lock. Only one process may hold an
          | exclusive lock for a given file at a time.
----------+------------------------------------------------
LOCK_NB   | Don't block when locking. May be combined
          | with other lock options using logical or.
----------+------------------------------------------------
LOCK_SH   | Shared lock. Multiple processes may each hold a
          | shared lock for a given file at the same time.
----------+------------------------------------------------
LOCK_UN   | Unlock.
 

Example

open(file,'w+') do |file|
  ## lock the file so that no one can use it. 
  file.flock(File::LOCK_EX)
  read(file_name).each do |row|
    file.puts jsonify(row)
  end
end 


Thanks.

What did I learn today?

Welcome to the what did I learn today series. The intention of this blog spot is to compose the stuff that I learnt day-to-day basics and jo...