Skip to content

Instantly share code, notes, and snippets.

@vigram
vigram / time_difference.rb
Last active December 28, 2015 10:21
Find time difference(in months,years,weeks..etc) between two dates.
=begin
Time difference (duration) in year, quarter, month, bi-week, week and day.
Usages:
TimeDifference.between(start_date, end_date).in_months
TimeDifference.between(start_date, end_date).in_years
=end
@vigram
vigram / simple_socket.rb
Created January 9, 2015 07:05
Simple TCP oriented messaging system
client-side:
~~~~~~~~~~~
require 'socket'
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets
puts line.chop
end
@vigram
vigram / sidekiq_tasks.rake
Created December 11, 2014 12:09
Rake task to restart Sidekiq process
# Usage: bundle exec rake sidekiq:restart RAILS_ENV=<environment name>
namespace :sidekiq do
sidekiq_pid_file = Rails.root+'tmp/pids/sidekiq.pid'
desc "Sidekiq stop"
task :stop do
puts "#### Trying to stop Sidekiq Now !!! ####"
if File.exist?(sidekiq_pid_file)
puts "Stopping sidekiq now #PID-#{File.readlines(sidekiq_pid_file).first}..."
@vigram
vigram / date.rb
Last active August 29, 2015 14:05
Extension for Date & DateTime classes
=begin
Author: Vigram K
Date: 27th August 2014
Title: Extension for Date & DateTime classes
Adds following methods for date object,
first_monday_of_month, first_tuesday_of_month .. first_sunday_of_month
last_monday_of_month, last_tuesday_of_month .. last_sunday_of_month
@vigram
vigram / date_formatter.rb
Last active December 28, 2015 04:39
Custom Date Format made easy
module DateFormatter
def self.included(base)
date_columns = base.columns.select{|column| ["date","datetime"].include?(column.sql_type) }
date_columns.map(&:name).reject{|col_name| ["created_at", "updated_at"].include?(col_name)}.each{|column|
base.class_eval do
define_method column do
read_attribute(column.to_sym).custom_format
end
@vigram
vigram / singleton_pattern.rb
Created September 9, 2013 17:12
Singleton Pattern in Ruby
module SingletonPattern
def self.included(base)
base.class_eval do
@@instance = base.class.new
def instance
@@instance
end
@vigram
vigram / linked_list.rb
Last active December 22, 2015 16:19
Linear Linked List Implementation in Ruby
class LinkedList
attr_accessor :list
def initialize
@list = []
end
def add_node(data)
node = Struct.new(:data, :next)
new_node = node.new(data, nil)