Class: EasyCard::Response

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/easycard/response.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_data) ⇒ Response

Returns a new instance of Response.



33
34
35
36
37
38
39
40
# File 'lib/easycard/response.rb', line 33

def initialize raw_data
  @raw_data = raw_data
  @parsed_data = JSON.parse(@raw_data)
  @balance = @parsed_data.pop[?B].to_i if @parsed_data.last[?B]
  @data = @parsed_data.map do |record|
    self.class.normalize_record(record)
  end
end

Instance Attribute Details

#balanceObject (readonly)

Returns the value of attribute balance.



10
11
12
# File 'lib/easycard/response.rb', line 10

def balance
  @balance
end

#dataObject (readonly)

Returns the value of attribute data.



10
11
12
# File 'lib/easycard/response.rb', line 10

def data
  @data
end

#parsed_dataObject (readonly)

Returns the value of attribute parsed_data.



10
11
12
# File 'lib/easycard/response.rb', line 10

def parsed_data
  @parsed_data
end

#raw_dataObject (readonly)

Returns the value of attribute raw_data.



10
11
12
# File 'lib/easycard/response.rb', line 10

def raw_data
  @raw_data
end

Class Method Details

.normalize_record(record) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/easycard/response.rb', line 13

def self.normalize_record record
  type = case record[?T]
  when ?D then :withdrawal
  when ?U then :deposit
  when '罰款' then :fine
  when '查無交易資料' then raise EasyCard::NotFound, record[?T]
  else raise EasyCard::Error, "未知類型:#{record}"
  end
  record[?L].gsub!('<BR>', ?-)
  {type: type, datetime: record[?D], location: record[?L], balance: record[?A], amount: record[?Q]}
end

.type_text(type) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/easycard/response.rb', line 25

def self.type_text type
  case type
  when :withdrawal then EasyCard::ColorString.red('扣款')
  when :deposit then EasyCard::ColorString.green('儲值')
  when :fine then EasyCard::ColorString.yellow('罰款')
  end
end

Instance Method Details

#as(format = nil) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/easycard/response.rb', line 42

def as format = nil
  case format
  when :json then to_json
  when :yaml then to_yaml
  when :table then to_s
  else data
  end
end

#line(id, record) ⇒ Object



58
59
60
61
# File 'lib/easycard/response.rb', line 58

def line id, record
  type = self.class.type_text(record[:type])
  '%3d | %19s | %s | %5s | %5s | %s' % [id, record[:datetime], type, record[:amount], record[:balance], record[:location]]
end

#to_sObject



51
52
53
54
55
56
# File 'lib/easycard/response.rb', line 51

def to_s
  ret = "%3s | %-17s | %s | %-3s | %-3s | %s\n" % %w[# 時間 種類 金額 餘額 地點]
  ret << "#{?-*3} | #{?-*19} | #{?-*4} | #{?-*5} | #{?-*5} | #{?-*20}\n"
  @data.each_with_index.map{|record, i| ret << line(i+1, record) << $/}
  ret
end