- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
class SomeModel < ActiveRecord::Base
after_save :some_method
def some_method
self.save
end
end
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−157
class SomeModel < ActiveRecord::Base
after_save :some_method
def some_method
self.save
end
end
Рекурсивная рекурсия рекурсивна.
−160
<div class="comment-content">
<% if comment.body.include?('[/quote]') %>
<% @text = Array.new %>
<% summ = '' %>
<% @text = simple_format(comment.body).split(' ') %>
<% namecheck = false %>
<% contentcheck = false %>
<% quotestart = false %>
<% donothing = true %>
<% quotecount = 0 %>
<% count_quotes = 0 %>
<% @text.each do |t| %>
<% if t.include?('[/quote]') %>
<% count_quotes ||= 0 %>
<% count_quotes += 1 %>
<% end %>
<% end %>
<% @text.each do |t| %>
<% if t.include?('[/quote]') %>
<% contentcheck = false %>
<% namecheck = false %>
<% t = t.gsub('[/quote]', '</div></div>') %>
<% elsif t.include?('[quote=') %>
<% namecheck = true %>
<% donothing = false %>
<% t = t.gsub('[quote=', '') %>
<% elsif t.include?(']') %>
<% t = t.gsub(']', '') %>
<% end %>
<% if donothing == false %>
<% if contentcheck == true and namecheck == true and t != '' and t != '<p>' and t != '</p>' %>
<% t = '<div class=quotecontent>' + '<div class=quotestart>' + '<div class=quotename>' + 'Цитата - ' + t + '</div>' %>
<% contentcheck = true %>
<% namecheck = false %>
<% elsif contentcheck == true and t != '' and t != '<p>' and t != '</p>' %>
<% t = '<div class=quotecontent>' + t %>
<% contentcheck = false %>
<% elsif namecheck == true and t != '' and t != '<p>' and t != '</p>' %>
<% t = '<div class=quotestart>' + '<div class=quotename>' + 'Цитата - ' + t + '</div>' %>
<% namecheck = false %>
<% contentcheck = true %>
<% end %>
<% end %>
<% summ = summ + t + ' ' %>
<% end %>
<% else %>
<% summ = comment.body %>
<% end %>
<%=raw simple_format(summ) %>
</div>
Вьюха списка комментариев. Когда это попало к верстальщику - он был мягко говоря шокирован.
−379
if city.present?
if city.city.present?
city = city.city
else
city = "NIL"
end
else
city = "NIL"
end
Нечто
−84
def self.allow_some_behaviour?
# better safe than sorry.
bool = !false ? !false : !!false
# type checking
if bool
# short circuit just in case
return !true;
elsif !bool
return !false
end
end
найдено в реальном проекте, работало в течении года где то. зачем это сделано - непонятно. почему не выпилили, тоже неясно.
−98
def confirmed
if self.confirmation
"Да"
elsif !self.confirmation
"Нет"
else
""
end
end
забавно:)
−102
Money.new(v[:amount].gsub('.','').to_i)
а вы умеете так переводить баксы в центы?
−100
# ищем позиции в гугле
def search(request, keyword, p = nil)
proxy = nil
# инициализация прокси
if p # обьект с прокси-серверами
proxy = "http://#{p.proxy}/" # случайный прокси
proxy_working = false
while not proxy_working
begin
timeout(5) { open(request, :proxy => proxy) }
rescue Timeout::Error
$log.put "bad broxy #{proxy}"
proxy = "http://#{p.proxy}/"
next
rescue Errno::ECONNREFUSED
$log.put "bad broxy #{proxy}"
proxy = "http://#{p.proxy}/"
next
rescue OpenURI::HTTPError
$log.put "bad broxy #{proxy}"
proxy = "http://#{p.proxy}/"
next
else
$log.put "working #{proxy}"
proxy_working = true
end
end
end
# код
−101
def actual?
if self.from <= Date.today
if self.to
if self.to >= Date.today
true
else
false
end
else
true
end
else
false
end
end
метод в модели, проверяющий ее актуальность
−109
monthes = ['Нулября', 'Января', 'Февраля', 'Марта', 'Апреля', 'Мая', 'Июня', 'Июля', 'Августа', 'Сентября', 'Октября', 'Ноября', 'Декабря']
Вот, оказывается, как лечится, что индексы в массиве начинаются с нуля, а номера месяца с 1
−106
def simpleEncrDecr( alphabet, alphabetKey, encrDecrWord, triger) #простой метод одну букву из алфавита заменяет другой
alphabet = alphabet.chars.to_a
alphabetKey = alphabetKey.chars.to_a
encrDecrWord = encrDecrWord.chars.to_a
if triger == 'encryption' then
for i in 0..encrDecrWord.length-1
encrDecrWord[i] = alphabetKey[alphabet.rindex(encrDecrWord[i])]
end
elsif triger == 'decryption'
for i in 0..encrDecrWord.length-1
encrDecrWord[i] = alphabet[alphabetKey.rindex(encrDecrWord[i])]
end
else
p "You is looser! :-)"
end
encrDecrWord.join
end
def manyAlphEncrDecr( alphabet, alpKey, encrDecrWord, triger) #для закодування нужное слово которое будет ключом
alphabet = alphabet.chars.to_a
encrDecrWord = encrDecrWord.chars.to_a
if triger == 'encryption' then
for i in 0..encrDecrWord.length-1
sum = alphabet.rindex(encrDecrWord[i])+alphabet.rindex(alpKey[i])
encrDecrWord[i] = alphabet[sum%alphabet.length]
end
elsif triger == 'decryption'
for i in 0..encrDecrWord.length-1
div = alphabet.rindex(encrDecrWord[i])-alphabet.rindex(alpKey[i])
encrDecrWord[i] = alphabet[div]
end
else
p "You is looser! :-)"
end
encrDecrWord.join
end
def permutationEncrDecr( permKeyNew, encrDecrWord, triger) #меняет местами буквы в соответствии с ключом, 1234 <=> 3241
encrDecrWord = encrDecrWord.chars.to_a
encrDecrWordNew = Array.new
if triger == 'encryption' then
for i in 0..encrDecrWord.length-1
encrDecrWordNew[i] = encrDecrWord[permKeyNew[i]]
end
elsif triger == 'decryption'
for i in 0..encrDecrWord.length-1
encrDecrWordNew[permKeyNew[i]] = encrDecrWord[i]
end
else
p "You is looser! :-)"
end
encrDecrWordNew.join
end
def frequencyAnalysis(textForAnalis) #частотный анализ текста (подсчет букв)
analisHash = Hash.new
for i in 0..textForAnalis.length-1
analisHash[textForAnalis[i]] = 0
end
for i in 0..textForAnalis.length-1
analisHash[textForAnalis[i]] += 1
end
puts "Frequency Analysis - #{analisHash}"
end
p "Alphabet - #{alphabet = ('0'..'z').to_a.join}"
print "Enter words for encryption/decryption:"
wordForEncryped = gets.chomp
print "Type method:\n1-simple\n2-many alphabetic\n3-permutation\n"
method = gets.chomp
case
when method == '1' then
puts "Key for alphabet - #{alphabetKey = alphabet.chars.to_a.shuffle.join}"
puts "Simple Encryped - #{encrypedWord = simpleEncrDecr( alphabet, alphabetKey, wordForEncryped, 'encryption')}"
frequencyAnalysis(encrypedWord)
puts "Simple Decryped - #{simpleEncrDecr( alphabet, alphabetKey, encrypedWord, 'decryption')}"
when method == '2' then
print "Enter word for many alphabetical encryption/decryption:"
wordForManyAlphKey = gets.chomp.chars.to_a
manyAlphKey = Array.new
for i in 0..wordForEncryped.length-1
manyAlphKey[i] = wordForManyAlphKey[i%wordForManyAlphKey.length]
end
puts "Many Alphabetic Encryped - #{encrWordForManyAlph = manyAlphEncrDecr( alphabet, manyAlphKey, wordForEncryped, 'encryption')}"
frequencyAnalysis(encrWordForManyAlph)
puts "Many Alphabetic Decryped - #{manyAlphEncrDecr( alphabet, manyAlphKey, encrWordForManyAlph, 'decryption')}"
when method == '3' then
print 'Please typed key(f.e. 23451):'
permKey = gets.chomp.chars.to_a
lengthForSum = permKey.length
newPermKey = Array.new
for i in 0..wordForEncryped.length-1
lengthForSum += permKey.length if i==lengthForSum
newPermKey[i] = permKey[i%permKey.length].to_i + lengthForSum - permKey.length-1
end
puts "Permutation Encryped - #{encrypedWordForPrem = permutationEncrDecr( newPermKey, wordForEncryped, 'encryption')}"
frequencyAnalysis(encrypedWordForPrem)
puts "Permutation Decryped - #{permutationEncrDecr( newPermKey, encrypedWordForPrem, 'decryption')}"
else p 'Incorect typed'
end
Методьі кодирования
1. простой метод одну букву из алфавита заменяет другой
2. для закодування нужное слово которое будет ключом
3. меняет местами буквы в соответствии с ключом, 1234 <=> 3241
4. частотный анализ текста (подсчет букв)
у каждого метода кроме 4 есть триггер - выбор в каком режиме метод будет работать (кодирование или декодирование)