Skip to content

Instantly share code, notes, and snippets.

@launchkit-codes
launchkit-codes / 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
@launchkit-codes
launchkit-codes / 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
@launchkit-codes
launchkit-codes / 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
@launchkit-codes
launchkit-codes / gsub.rb
Created January 27, 2015 12:48
Ruby String#gsub with hash params
"olo".gsub(/[ol]/, 'o' => 'l', 'l' => 'o')
# output
#
# 'lol'
@launchkit-codes
launchkit-codes / require_relative.rb
Last active August 29, 2015 14:14
Understand `require_relative`
# require_relative :
#
# Ruby tries to load the library named string relative to the requiring file’s path.
# If the file’s path cannot be determined a LoadError is raised.
# If a file is loaded true is returned and false otherwise.
#
# Tree directory:
#
# ./
# |- test
@launchkit-codes
launchkit-codes / display_complex_objects.rb
Last active August 29, 2015 14:15
`p` and `puts` Behind The Scene
# `puts` method calls `to_s` method when a class is given as param
# `p` method calls `inspect` method when a class is given as param
class Factory
def initialize
@workers = { workers: [] } # A lot of workers
@machines = { machines: [] } # A lot of machines
end
def add_worker(name)
@launchkit-codes
launchkit-codes / Gemfile
Created February 17, 2015 08:42
Specify similar configuration in groups of a Gemfile
# Gemfile consists of plain Ruby
# So it's authorized to do this:
branch = 'develop'
group :development do
%(a b c d).each do |lib|
gem lib, :git => "https://github.com/abc/#{lib}.git", :branch => branch
end
end
@launchkit-codes
launchkit-codes / ext_ascii.rb
Created February 24, 2015 13:40
Display Extended-ASCII characters in RUBY
# more information here: http://ruby-doc.org//core-2.2.0/Integer.html#method-i-chr
puts 219.chr #=> "?"
puts 219.chr(Encoding::UTF_8) #=> "Û"
@launchkit-codes
launchkit-codes / interpolation.rb
Created March 9, 2015 09:46
Interpolation Behind the Scene
class ValentineDay
def to_s
"I love you"
end
end
puts "#{ValentineDay.new}" # => I love you
@launchkit-codes
launchkit-codes / closure.rb
Created March 20, 2015 10:44
What's closure concept?
def add(a)
return Proc.new do |b|
a + b
end
end
addition = add(4)
puts addition.call(5) # => 9