Skip to content

Instantly share code, notes, and snippets.

View mehdi-farsi's full-sized avatar

Mehdi FARSI mehdi-farsi

View GitHub Profile
@mehdi-farsi
mehdi-farsi / modules_and_classes.rb
Last active August 29, 2015 14:09
Ruby Method-Calling Hierarchy Between Modules and Classes
# Ruby Method-Calling Hierarchy.
#
# When a method is called Ruby :
#
# 1 - searches the method in class.
#
# 2- searches the method in each included modules
# from the last one to the first one.
#
# Study Case:
@mehdi-farsi
mehdi-farsi / proc_block_lambda.rb
Created November 17, 2014 23:36
Difference between Procs, Blocks, Lambdas in Ruby
#
# Main difference: Procs are objects, blocks are not.
#
# The '&' tells ruby to turn the proc into a block.
#
class Array
def map2
new_ary = []
self.each do |elem|
@mehdi-farsi
mehdi-farsi / head.rb
Created November 19, 2014 15:03
Ruby Net::HTTP Get header without body from an HTTP request
require "net/http"
uri = URI('YOUR URL')
req = Net::HTTP::Head.new(uri)
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
@mehdi-farsi
mehdi-farsi / _links.html.erb
Created December 3, 2014 10:26
Sort by ActiveRecord column
@mehdi-farsi
mehdi-farsi / GET.txt
Created December 7, 2014 18:25
Pass an array as parameter to an HTTP request
# Example:
#
# Wanna pass an array of categories via a GET request.
http://YOUR_URL/?category[]=handbag&category[]=wallet
@mehdi-farsi
mehdi-farsi / proc_and_lambda.rb
Created December 9, 2014 16:53
Difference between Proc and Lambda
# Procs and Lambdas. They are both a Proc object.
#
# The main differences:
#
# 1- Lamdbas are strict about argument number instead of Procs.
# 2- Lambda :return returns out the scope. Proc :return returns out of the calling scope.
# Lamdbas are strict about argument number instead of Procs.
l = lambda { |word| puts word }
@mehdi-farsi
mehdi-farsi / habtm_scope.rb
Created December 17, 2014 15:48
Using scope with HABTM
class Category < ActiveRecord::Base
has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
has_and_belongs_to_many :categories
# :c can be an array of categories.
scope :by_categories, ->(c) { includes(:categories).where(categories: {id: c}) }
end
@mehdi-farsi
mehdi-farsi / my_tree.rb
Last active August 29, 2015 14:12
Getting started with Binary Trees and Ruby
# Example:
#
# 1
# / \
# 2 12
# /
# 4
class Node
attr_accessor :left, :right, :value
@mehdi-farsi
mehdi-farsi / return_a_class.rb
Created January 20, 2015 10:02
Return a Class in Ruby
class Hello
def self.world
puts 'Hello World !'
end
end
def return_hello
return Hello
end
@mehdi-farsi
mehdi-farsi / gsub.rb
Created January 27, 2015 12:48
Ruby String#gsub with hash params
"olo".gsub(/[ol]/, 'o' => 'l', 'l' => 'o')
# output
#
# 'lol'