Module: YamlHelper
- Defined in:
- lib/kwalify/util/yaml-helper.rb
Class Method Summary collapse
-
.create_hashtable(hashlist, primarykey, flag_duplicate_check = true) ⇒ Object
create a hash table from list of hash with primary key.
-
.get_value(obj, path) ⇒ Object
get nested value directly.
-
.untabify(input) ⇒ Object
expand tab character to spaces.
Class Method Details
.create_hashtable(hashlist, primarykey, flag_duplicate_check = true) ⇒ Object
create a hash table from list of hash with primary key.
ex.
hashlist = [
{ "name"=>"Foo", "gender"=>"M", "age"=>20, },
{ "name"=>"Bar", "gender"=>"F", "age"=>25, },
{ "name"=>"Baz", "gender"=>"M", "age"=>30, },
]
hashtable = YamlHelper.create_hashtable(hashlist, "name")
p hashtable
# => { "Foo" => { "name"=>"Foo", "gender"=>"M", "age"=>20, },
"Bar" => { "name"=>"Bar", "gender"=>"F", "age"=>25, },
"Baz" => { "name"=>"Baz", "gender"=>"M", "age"=>30, }, }
43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/kwalify/util/yaml-helper.rb', line 43 def self.create_hashtable(hashlist, primarykey, flag_duplicate_check=true) hashtable = {} hashlist.each do |hash| key = hash[primarykey] unless key riase "primary key '#{key}' not found." end if flag_duplicate_check && hashtable.key?(key) raise "primary key '#{key}' duplicated (value '#{hashtable[key]}')" end hashtable[key] = hash end if hashlist return hashtable end |
.get_value(obj, path) ⇒ Object
get nested value directly.
ex.
val = YamlHelper.get_value(obj, ['aaa', 0, 'xxx'])
This is equal to the following:
begin
val = obj['aaa'][0]['xxx']
rescue NameError
val = nil
end
72 73 74 75 76 77 78 79 |
# File 'lib/kwalify/util/yaml-helper.rb', line 72 def self.get_value(obj, path) val = obj path.each do |key| return nil unless val.is_a?(Hash) || val.is_a?(Array) val = val[key] end if path return val end |
.untabify(input) ⇒ Object
expand tab character to spaces
ex.
untabified_str = YamlHelper.untabify(tabbed_str)
- input
-
String or IO
19 20 21 22 23 24 25 |
# File 'lib/kwalify/util/yaml-helper.rb', line 19 def self.untabify(input) s = '' input.each_line do |line| s << line.gsub(/([^\t]{8})|([^\t]*)\t/n) { [$+].pack("A8") } end return s end |