Skip to content

Instantly share code, notes, and snippets.

@huseyin
Last active October 7, 2015 21:44
Show Gist options
  • Save huseyin/38f77836d372e4214577 to your computer and use it in GitHub Desktop.
Save huseyin/38f77836d372e4214577 to your computer and use it in GitHub Desktop.
# encoding: utf-8
module Fontize
class FontizeError < StandardError
end
class ArgumentError < FontizeError
end
class NoKeyError < FontizeError
end
def fontize(options = {})
begin
style = options.fetch(:style)
rescue KeyError => err
raise(NoKeyError, err)
end
# Stil ile alınan argüman stoktaki stillerde bulunuyor mu?
# Bulunmuyor ise exception çıktısı üret.
unless font_styles.include?(style)
raise(ArgumentError, "#{style} - no such argument")
end
# Stilize edilmek istenen string daha önceden stilize edilmiş mi kontrol
# et. Edilmiş ise multi stilize özelliğini devreye sok.
#
# Örneğin,
#
# "\e[1mfoobar\e[0m"
#
# şeklinde stilize edilmiş bir string, yeniden farklı
# bir stil ile stilize edilmek istenirse,
#
# "\e[1m\[7mfoobar\e[0m\e[0m"
#
# gibi karışıklığa gitmek yerine
#
# "\e[7;1mfoobar\e[0m"
#
# gibi bir basitlik tercih edilsin.
if self.fontized?
multi_fontize self, font_styles[style]
else
fontize_template self, font_styles[style]
end
end
# Kaynak string daha önceden fontize edilmiş mi kontrol et.
def fontized?
scan = self.scan(/\033\[([0-9;]+)m([a-zA-Z ]+)/)
scan.empty? ? false : true
end
private
def font_styles
{
default: 0,
bold: 1,
underline: 4,
swap: 7,
middleline: 9,
}
end
def fontize_template(text, style)
"\033[#{style}m#{text}\033[0m"
end
def multi_fontize(text, style)
tmp = %()
text.each_char { |c| tmp << c }
# Stil ekleme işlemini tmp isimli başka bir değişkende text değişkenine
# kuyruk takılmamış olarak yap. Öteki türlü text değişkenide tmp
# değiştikçe değişecektir.
tmp.insert(2, "#{style};")
end
end
@huseyin
Copy link
Author

huseyin commented Oct 7, 2015

Örneklendirmek gerekirse,

ornek.rb

# Unutmayalım ki betik LOAD_PATH'te tanımlı değil
require_relative 'fontize'

class String
  include Fontize
end

puts "foobar".fontize(:style => :bold).fontize(:style => :underline) # ... gider

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment