Skip to content

Instantly share code, notes, and snippets.

View xpepper's full-sized avatar
💭
😏

Pietro Di Bello xpepper

💭
😏
View GitHub Profile
class Movie
REGULAR = 0
NEW_RELEASE = 1
CHILDRENS = 2
attr_reader :title
attr_reader :price_code
def initialize(title, price_code)
@title, @price_code = title, price_code
@xpepper
xpepper / my_struct.rb
Last active November 4, 2017 10:27
My own (bare and simple) implementation of ruby's Struct core class
class MyStruct
#=> self is MyStruct
def self.new(*attributes)
#=> self is MyStruct
Class.new do
#=> self is the class instance
attr_accessor(*attributes)
end
end
@xpepper
xpepper / struct.rb
Created April 11, 2013 21:41
My solution to Dave Thomas' exercise in 6th lession
class Struct
@children = []
def self.inherited(child)
@children << child
end
class << self
attr_accessor :children
end
end
@xpepper
xpepper / reimplementing_module_include.md
Last active December 16, 2015 04:18
Reimplementing Module#include method

Reimplementing Module#include method (my_include method):

  1. my_include takes one or many modules
  2. it goes on a reverse traversal and for each module it adds its features to self
  3. calls an home-made hook method
class Module
  def my_include(*modules)
 modules.reverse_each do |each_module|

Ruby #4.

class_eval vs. instance_eval

Module#class_eval:

  1. set self to the receiver for the duration of the block
  2. set the current class to class/module which is the receiver
  3. can be called only on classes and modules
  • => it's like re-opening the class/module
  • => the scope of the block is that class
class ShippingOption
@options = []
def self.inherited(child)
@options << child
end
def self.for(weight, international)
@options.select { |o| o.can_ship?(weight, international)}
end
@xpepper
xpepper / cut_crontab.sh
Created April 17, 2013 07:29
Removing the first 11 lines from a crontab
crontab -l > CT; sed -i -e "1,11d" CT; crontab CT; rm -f CT; crontab -l
@xpepper
xpepper / charesc.rb
Created April 17, 2013 21:14
charesc gem reloaded
class Module
m = instance_method(:const_missing)
define_method :const_missing do |name|
if name.to_s =~ /^U([0-9a-fA-F]{4})$/
[$1.to_i(16)].pack("U*")
else
m.bind(self).call(name)
end
end
class Color
def self.const_missing(name)
const_set(name, new(name.to_s.downcase))
end
def initialize(color_name)
@color_name = color_name
end
def to_s
@color_name
class Enum
def self.new
Class.new do
def self.const_missing(name)
const_set(name, new)
end
end
end
end