Module: Ns::Util

Extended by:
Util
Included in:
Util
Defined in:
lib/ns_service_pack/util.rb

Instance Method Summary collapse

Instance Method Details

#concat_url(prefix_url = '', url = '') ⇒ Object



7
8
9
10
11
# File 'lib/ns_service_pack/util.rb', line 7

def concat_url(prefix_url = '', url = '')
  prefix_url = prefix_url.to_s
  sep = (prefix_url[-1, 1] == '/' || url[0, 1] == '/') ? '' : '/'
  "#{prefix_url}#{sep}#{url}"
end

#params_query(base_url = '', query_params = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/ns_service_pack/util.rb', line 13

def params_query(base_url = '', query_params = {})
  query_str = query_params.respond_to?(:to_query) ? query_params.to_query : query_params.to_a.map{|a| a.join('=')}.join('&')
  base_url = base_url.to_s
  unless query_str.blank?
    sep = if base_url[-1, 1] =~ /\?|&/ 
            ''
          else
            if base_url.include?('?')
              '&'
            else
              '?'
            end
          end
  end
  "#{base_url}#{sep}#{query_str}"
end

#yamlize(hash_or_array = {}, file_name = nil) ⇒ Object

将一个hash和array写入data下的yaml结构中



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ns_service_pack/util.rb', line 31

def yamlize(hash_or_array = {}, file_name = nil)
  return if hash_or_array.nil?
  hash = if hash_or_array.is_a?(Array)
    hash_or_array.inject({}) do |r, k|
      r[k] = nil
      r
    end
  else
    hash_or_array
  end

  method_key = file_name.nil? ? "hash" : file_name.to_s
  name = "#{method_key}_#{Time.now.to_i}"
  file = "#{Rails.root}/data/#{name}.yml"
  path = File.dirname(file)
  FileUtils.mkpath(path) unless File.directory?(path)
  File.open(file, 'w+') do |f|
    #保证生成的文件是utf8编码
    f.puts "#==本文件由Nsp生成于#{Time.now.to_s(:db)},可根据情况编辑"
    f.puts YAML.dump(method_key.to_sym=>hash)
  end
  puts "Generate a yaml file in #{file}"
  file
end