Skip to content

Instantly share code, notes, and snippets.

View leonid-shevtsov's full-sized avatar
🇺🇦
Help Ukraine Win

Leonid Shevtsov leonid-shevtsov

🇺🇦
Help Ukraine Win
View GitHub Profile

Code that does not run is code that rots

In Ruby, there is absolutely no guarantee that a method's declared signature will match the call signature. The only practical way to ensure this is to execute the call.

Thus, if you have code that is not covered by unit tests, you rely on manual testing - and production - to check that it even links, let alone does what you expect.

From my experience with explicit typing, it eliminates a huge class of refactoring mistakes, where you forget to update a method or a call signature. In Ruby, instead of explicit typing, we have unit tests.

This, to me, is the big reason to write unit tests in Ruby - not because it's more productive, or makes for better code. Code that verifiably links is reason enough to write them.

#!/bin/bash
# Put in $PATH/git-pr; chmod +x
# Call with `git pr` to open a compare view for the current branch and a pull request from that
# Depends on https://hub.github.com/
hub compare dev..`git rev-parse --abbrev-ref HEAD`
@leonid-shevtsov
leonid-shevtsov / gist:5903356
Created July 1, 2013 18:32
Fixed auto-link web search for Markdown Service Tools
require 'net/http'
require 'net/https'
require 'openssl'
require 'uri'
def fetch_with_redirect(uri_str, limit = 10)
return nil if limit==0
uri = URI.parse(uri_str)
http = Net::HTTP.new(uri.host, uri.port)
; Switch keyboard layouts with Win+Space on Windows
#Space::PostMessage, 0x50, 2, 0,, A
$ python2.6 test.py
(<type 'exceptions.OSError'>, OSError(32, 'Broken pipe'), <traceback object at 0x1096aa950>)
Traceback (most recent call last):
File "test.py", line 9, in <module>
lines=sp.communicate(inp)[0]
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 691, in communicate
return self._communicate(input)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1222, in _communicate
bytes_written = os.write(self.stdin.fileno(), chunk)
OSError: [Errno 32] Broken pipe

Помогите протестировать патч. Срочно. Патч представляет собой бекпорт из Ruby 2.0.0 бага http://bugs.ruby-lang.org/issues/5570 о том, что Ruby неправильно понимает переменные окружения с не-латинским содержимым (грубо говоря), включая и название домашней папки, из-за чего, например, ломается установка гемов.

От вас нужно: виндоус, предпочтительно на виртуалке (за сохранность физической машины ответственности не несу).

  1. Скачиваем пропатченный RubyInstaller 1.9.3 https://www.dropbox.com/s/vkx3ia0x1va370l/rubyinstaller-ru.exe

  2. Создаем пользователя с русским именем ("Руби", например)

  3. Устанавливаем из-под него Ruby

# Connect Opscode repository
echo "deb http://apt.opscode.com/ `lsb_release -cs`-0.10 main" | tee /etc/apt/sources.list.d/opscode.list
mkdir -p /etc/apt/trusted.gpg.d
gpg --keyserver keys.gnupg.net --recv-keys 83EF826A
gpg --export [email protected] | tee /etc/apt/trusted.gpg.d/opscode-keyring.gpg > /dev/null
# Install chef
apt-get update -qq
echo "chef chef/chef_server_url string none" | debconf-set-selections && apt-get install chef -y -q
# Stop and disable the chef-client service since we're only using chef-solo
/etc/init.d/chef-client stop
@leonid-shevtsov
leonid-shevtsov / proposal.markdown
Created May 10, 2012 09:34
DOU Hackathon Dnepr-May-2012 project proposal

Архиватор Твиттера

Проблема

  • Старые данные Твиттера невозможно или сложно найти: старые ретвиты, упоминания пользователя / хештега / произвольной фразы и т.п.
  • Твиты хранятся только в твиттере, а, следовательно, рискуют быть утерянными в случае сбоя/удаления старых данных/удаления пользователя
  • Многие люди пользуются твиттером как блогом, публикуя полезную информацию только в твиттер, несмотря на то, что просмотр старых твитов очень неудобен (нет поиска, архива-календаря и т.п.)

Решение

@leonid-shevtsov
leonid-shevtsov / gist:2550423
Created April 29, 2012 13:22
Like find(:first), but asserts that query returns exactly one element. Works with scopes.
class MyModel < ActiveRecord::Base
def self.one(find_hash={})
results = find(:all, find_hash)
if results.size != 1
raise "Expected one record, found #{results.size}"
else
return results[0]
end
end
end