Skip to content

Instantly share code, notes, and snippets.

Benchmark.bm do |x|
hash = {:foo => "foo"}
class Item
def initialize
@foo = "foo"
end
def foo
@foo
end
end
penis
class User
include Mongoid::Document
[:street_address, :phone_number, :email_address].each do |f|
embeds_many f.to_s.pluralize.to_sym do
def [](key)
detect {|e| e.name.eql?(key.to_s)} || build(:name => key.to_s)
end
end
define_method f do
class User
include Mongoid::Document
alias_method :name_orig, :name
def name
class << self
alias_method :name, :name_orig
end
self[:name].nil? ? self[:name] = Name.new : self[:name]
end
@kke
kke / gist:2133704
Created March 20, 2012 10:01
mechanize ytj by bid scraper
require 'mechanize'
def get_ytj(bid)
agent = Mechanize.new
agent.user_agent = 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)'
search_form = agent.get('http://www.ytj.fi/yrityshaku.aspx').form_with(:name => 'aspnetForm')
search_form.field_with(:name => '_ctl0:ContentPlaceHolder:ytunnus').value = bid
page = search_form.submit(search_form.button_with(:value => 'Hae yritykset')).link_with(:text => bid).click
Hash[*page.search("//div[@id='detail-result']//table/tr").collect{|row| row.search('td')[0..1].collect{|cell| cell.inner_text.chomp.gsub(/^\s+/, "").gsub(/\s+$/, "")}}.flatten]
rescue
@kke
kke / super-id.rb
Created April 3, 2012 10:14
super id
require 'socket' # for gethostname
class LogId
@@hostname = Socket.gethostname
@@hostid = @@hostname.gsub('.', '').downcase.each_char.inject(""){|r,c| r += c.ord.to_s}.to_i
@@hostid_short = @@hostname.gsub('.', '').downcase.each_char.inject(0){|r,c| r += c.ord}
def self.get(*opts)
# opts = [:host] if opts.empty? # modify defaults
time = Time.now.usec.to_i
require 'benchmark'
Benchmark.bm do |x|
test = ["test", 1]
x.report(" rescue") { 100000.times { test.collect{|x| x.strip! rescue nil} } }
test = ["test", "test"]
x.report("no rescue") { 100000.times { test.collect{|x| x.strip!} } }
test = ["test", 1]
x.report(" respond") { 100000.times { test.collect{|x| x.strip! if x.respond_to?(:strip!)} } }
end
class Zuper
def self.inherited(child)
puts "Zuper says: #{child}"
end
end
class KidOne < Zuper
end
# Zuper says: KidOne
@kke
kke / gist:5528794
Last active December 17, 2015 01:29
<% apples = Apple.find(:all) %> # now apples = [apple1, apple2, apple3]
<ul>
<% apples.each do |item| %> # take apples one by one, always calling the current apple "item"
<li>id: <%= item.id %></li> # item.id = id of the apple currently being processed
<li>name: <%= item.name %></li> # item.name = name of the apple currently being processed
<li>price: <%= item.price %></li># item.price = price of apple currently being processed
<% end %>
</ul>
@kke
kke / case.rb
Created May 15, 2013 09:37
Case-when a class
def format_return(out_class)
case out_class
when UserParamsOut
...
when Hash
{:hello => "howdy"}
else
"helloes!"
end
end