Module: RockFintech::Utils

Defined in:
lib/rock_fintech/utils.rb

Class Method Summary collapse

Class Method Details

.api_result(request_params, response) ⇒ Object

api 通用返回数据结构

Parameters:

  • request_params (Object)

    请求参数

  • response (Object)

    响应对象

Returns:

  • (Object)


63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rock_fintech/utils.rb', line 63

def self.api_result(request_params, response)
  {
    result: 'P', # 默认
    request_params: request_params,
    response: response,
    flow_id: response.nil? ? nil : response.flow_id,
    code: response.nil? ? nil : response.data[:code],
    msg: response.nil? ? nil : response.data[:msg],
    data: response.nil? ? nil : response.data,
  }
end

.gen_flow_id(time = Time.now.to_i) ⇒ String

通过时间,返回唯一一个24位flow id(支持分布) 同一秒,同一台机器,同一个进程,最多可以产生 16777214 个不一样的订单号

Examples:

JytPay::Utils.gen_flow_id

Parameters:

  • time (Integer) (defaults to: Time.now.to_i)

    时间(默认是 now)

Returns:

  • (String)


41
42
43
44
45
46
47
48
49
50
# File 'lib/rock_fintech/utils.rb', line 41

def self.gen_flow_id(time=Time.now.to_i)
  machine_id = Digest::MD5.digest(::Mac.addr).unpack("N")[0]
  process_id = Process.pid % 0xFFFF

  @counter ||= 0
  @counter += 1
  count = (@counter) % 0xFFFFFF

  return [ time, machine_id, process_id, count << 8 ].pack("N NX lXX NX").unpack("H*")[0].force_encoding('UTF-8')
end

.get_uuid(time = Time.now.to_i) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rock_fintech/utils.rb', line 20

def self.get_uuid(time=Time.now.to_i)
  machine_id = Digest::MD5.digest(::Mac.addr).unpack("N")[0]
  process_id = Process.pid % 0xFFFF

  @uuid_counter ||= 0
  @uuid_counter += 1
  count = (@uuid_counter) % 0xFFFFFF

  uid = [ time, machine_id, process_id, count << 8 ].pack("N NX lXX NX").unpack("H*")[0].force_encoding('UTF-8')

  return 'uuid' + uid
end

.random_key(size = 16) ⇒ String

随机产生 size 位字符串(大小写,数字组成)

Parameters:

  • size (Int) (defaults to: 16)

    需要的位数,默认 16 位

Returns:

  • (String)

    随机字符串



55
56
57
# File 'lib/rock_fintech/utils.rb', line 55

def self.random_key(size=16)
  ((0..9).to_a + ('a'..'z').to_a + ('A'..'Z').to_a).sample(size).join()
end

.symbolize_keys(hash) ⇒ Hash

把 hash 中的 key,都转化为 symbol 类型

Parameters:

  • hash (Hash)

    需要更改的 hash

Returns:

  • (Hash)

    更改后的 hash



12
13
14
15
16
17
18
# File 'lib/rock_fintech/utils.rb', line 12

def self.symbolize_keys(hash)
  new_hash = {}
  hash.each do |key, value|
    new_hash[(key.to_sym rescue key) || key] = value
  end
  new_hash
end