Module: Kwartz::Util
- Defined in:
- lib/kwartz/util.rb
Class Method Summary collapse
-
.intern_hash_keys(obj, done = {}) ⇒ Object
convert hash’s key string into symbol.
-
.pattern_to_regexp(pattern) ⇒ Object
convert string pattern into regexp.
-
.select_with_patterns(list, patterns) ⇒ Object
select items from list with patterns.
-
.untabify(str, width = 8) ⇒ Object
expand tab characters to spaces.
Class Method Details
.intern_hash_keys(obj, done = {}) ⇒ Object
convert hash’s key string into symbol.
ex.
hash = YAML.load_file('foo.yaml')
intern_hash_keys(hash)
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/kwartz/util.rb', line 51 def intern_hash_keys(obj, done={}) return if done.key?(obj.__id__) case obj when Hash done[obj.__id__] = obj obj.keys.each do |key| obj[key.intern] = obj.delete(key) if key.is_a?(String) end obj.values.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end when Array done[obj.__id__] = obj obj.each do |val| intern_hash_keys(val, done) if val.is_a?(Hash) || val.is_a?(Array) end end end |
.pattern_to_regexp(pattern) ⇒ Object
convert string pattern into regexp. metacharacter ‘*’ and ‘?’ are available.
ex.
pattern_to_regexp('*.html') #=> /\A(.*)\.html\z/
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/kwartz/util.rb', line 78 def pattern_to_regexp(pattern) i = 0 len = pattern.length s = '\A' while i < len case ch = pattern[i] when ?\\ ; s << Regexp.escape(pattern[i+=1].chr) when ?* ; s << '(.*)' when ?? ; s << '(.)' else ; s << Regexp.escape(ch.chr) end i += 1 end s << '\z' return Regexp.compile(s) end |
.select_with_patterns(list, patterns) ⇒ Object
select items from list with patterns.
ex.
patterns = %w[user_*]
names = %w[user_name user_age error_msg]
select_with_patterns(list, patterns) #=> ['user_name', 'user_age']
104 105 106 107 |
# File 'lib/kwartz/util.rb', line 104 def select_with_patterns(list, patterns) regexp_list = patterns.collect { |pattern| pattern_to_regexp(pattern) } return list.select { |item| regexp_list.any? { |rexp| rexp =~ item } } end |
.untabify(str, width = 8) ⇒ Object
expand tab characters to spaces
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/kwartz/util.rb', line 20 def untabify(str, width=8) list = str.split(/\t/) last = list.pop buf = [] list.each do |s| column = (pos = s.rindex(?\n)) ? s.length - pos - 1 : s.length n = width - (column % width) buf << s << (" " * n) end buf << last return buf.join end |