Skip to content

Instantly share code, notes, and snippets.

@swistak35
swistak35 / test.rb
Created July 18, 2012 19:01
Playing with ObjectSpace and GC
class Vehicle
class << self
attr_accessor :count
def finalize(id)
@count -= 1
end
def all #returns an array of all Vehicle objects
ObjectSpace.each_object(Vehicle).to_a
end
@swistak35
swistak35 / functional_ruby.rb
Created August 12, 2012 21:20
Functional equivalent to oop code in ruby
# Functional:
new_person = ->(name,birthdate,gender,title,id=nil) {
return ->(attribute) {
return id if attribute == :id
return name if attribute == :name
return birthdate if attribute == :birthdate
return gender if attribute == :gender
return title if attribute == :title
nil
@swistak35
swistak35 / dci_with_hacks.rb
Last active December 14, 2015 11:08
DCI using EVIL.RB, Wroc_Love.rb 2013
# Firstly, install gems: 'evilr' and 'include'
# Example with User in a shop application.
# He has two roles
# - buyer (with money on the account and so on)
# - reviewer (he can review books he bought)
require 'evilr'
require 'include'
params[:foo] = DecimalSupport.parse_model_decimals(params[:foo], Foo)
@swistak35
swistak35 / observer.rb
Created March 20, 2013 22:35
Cutting decimals observer
def before_save(model)
model.class.columns.each do |column|
if column.type == :decimal
int_part, frac_part = model.send(column.name).to_s.split(".")
new_value = [int_part, frac_part[0...column.scale]].join(".")
model.send("#{column.name}=", new_value)
end
end
end
@swistak35
swistak35 / log
Created September 2, 2013 17:33
Enumerable#find_and_replace(cond, &block)
1.9.3p362 :002 > [1,2,3,4,5].find_and_replace(:odd?, &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :003 > [1,2,3,4,5].find_and_replace(Proc.new(&:odd?), &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :005 > [1,2,3,4,5].find_and_replace(->(x) { x.odd? }, &:to_s)
=> ["1", 2, "3", 4, "5"]
1.9.3p362 :006 > [1,2,3,4,5].find_and_replace(->(x) { x.odd? }) do |x|
1.9.3p362 :007 > x.to_s
1.9.3p362 :008?> end
=> ["1", 2, "3", 4, "5"]
@swistak35
swistak35 / test_rw.ml
Last active January 2, 2016 01:19
Strange behavior of IO in Ocaml. It firstly reads value for scanf, and after that printf all stuff (even those, which it should print before scanf). test_rw2 contains even simpler example.
type ast = Cons of ast * ast
| Write
| Read
open Printf
open Scanf
let myVar = ref 0
let set_myVar x =
~% echo "" > bar
~% cat bar
~% irb
1.9.3-p547 :001 > f = File.open("bar", "w")
=> #<File:bar>
1.9.3-p547 :002 > f.write("test1")
=> 5
1.9.3-p547 :003 >
zsh: suspended irb
t1 = Thread.new do
f = File.open("bar", "w")
sleep(rand(5) + 2)
f.write("test_1")
f.close
end
t2 = Thread.new do
f = File.open("bar", "w")
@swistak35
swistak35 / gist:e79976173b309fa0cf67
Created February 21, 2015 00:09
$... are global variables, except that no
str = "The quick fox and dog trololo"
/fox/.match(str)
def search2(str)
/and/.match(str)
puts "Inside method2: #{$&}"
end
def search(str)
/dog/.match(str)