Module: Lanmao::Utils

Defined in:
lib/lanmao/utils.rb

Class Method Summary collapse

Class Method Details

.api_result(request_params, response) ⇒ Object

api 通用返回数据结构

Parameters:

  • request_params (Object)

    请求参数

  • response (Object)

    响应对象

Returns:

  • (Object)


59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/lanmao/utils.rb', line 59

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],
    error_code: response.nil? ? nil : response.data[:errorCode],
    error_msg: response.nil? ? nil : response.data[:errorMessage],
    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)


37
38
39
40
41
42
43
44
45
46
# File 'lib/lanmao/utils.rb', line 37

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



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/lanmao/utils.rb', line 16

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)

    随机字符串



51
52
53
# File 'lib/lanmao/utils.rb', line 51

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
# File 'lib/lanmao/utils.rb', line 12

def self.symbolize_keys(hash)
  hash.with_indifferent_access
end