Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
AJFaraday / wow.rb
Created April 12, 2017 15:52
Dynamically extending an AR class with a validation
# This works like a dream!
module FooValidator
attr_accessor :foo
def FooValidator.extended(base)
base.singleton_class.validates_presence_of :foo
end
end
u = User.first
u.extend(FooValidator)
20:10:13 238 but it missed.
20:10:13 238 Alice attacks Bob
20:10:13 238 it has no effect.
20:10:13 238
20:10:13 238 ["Alice: 10", "Bob: 10", "Charlie: 10"]
20:10:13 238
20:10:13 238 but it missed.
20:10:13 238 Bob attacks Charlie
20:10:13 238 it has no effect.
20:10:13 238
@AJFaraday
AJFaraday / turn.rb
Created April 10, 2017 16:23
Example usage pattern
# Previous example in github.com/ajfaraday/re-rpg in script/simple_battle.rb
character.actions
# [:attack, :fire, :block, :heal, :"full heal"]
character.action(:attack, target)
# purely hypothetical, mostly unimplemented
@AJFaraday
AJFaraday / 1_mil_dice.rb
Last active April 8, 2017 22:26
1 million dice
x = Hash.new(0)
1000000.times.collect{ ChanceGenerator.roll_bag([6,6]).sum }.collect{|v| x[v] += 1 }
x.sort.each{|k,v| puts "#{k}: #{v} times"}
=begin
2: 27587 times
3: 55513 times
4: 83018 times
5: 111126 times
6: 138510 times
@AJFaraday
AJFaraday / game.rb
Created March 25, 2017 19:10
game_stats.rb
class Game
def initialize
@characters = []
@characters << Character.new("Alice", 5, 2, 90, 10)
@characters << Character.new("Bob", 5, 2, 50, 50)
@characters << Character.new("Carol", 5, 2, 10, 90)
end
def play
while play_turn
@AJFaraday
AJFaraday / puzzled.rb
Created March 14, 2017 14:11
How can I do this
# underpants
data = [
{a: 1, b: 1, c: 'a'},
{a: 1, b: 2, c: 'b'},
{a: 2, b: 2, c: 'c'}
]
# ?
new_data = transform_data(data)
# Fun fact: Rails relation methods have an argument which doesn't appear to do anything
task = Task.first
task.created_by_user
# a user
task.created_by_user(true)
task.created_by_user('anything here')
task.created_by_user({some: 'irrelevant', attributes: true})
# no errors, user is returned.
task.created_by_user(1,2)
@AJFaraday
AJFaraday / benchmarking.rb
Last active December 5, 2016 16:37
Which one is more efficient?
require 'benchmark'
puts Benchmark.measure do
1000.times{method1(array)}
end
# ...
# 0.020000 0.010000 0.030000 ( 0.027314)
puts Benchmark.measure do
1000.times{method2(array)}
end
describe EekController do
it 'should return some json' do
get :info
response.should eq(Eek.info.to_json) # This will hang rspec
end
it 'should not hang like this' do
get :info
response.body.should eq(Eek.info.to_json) # This will run fine, maybe pass. maybe fail.
@AJFaraday
AJFaraday / evil.rb
Created November 23, 2016 09:33
evil.rb
class Object
def method_missing(m, *args, &block)
return true
end
end
45.foo
# => true