ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Part 2 က program ကို ပိတ်လိုက်တာနဲ့ task အားလုံး ပျောက်သွားတဲ့အထိ အလုပ်လုပ်ပါတယ်။ Part 3 က tracker ကို file ထဲ သိမ်းပြီး startup မှာ ပြန်ဖတ်လို့ မနက်ဖြန် session က ဒီနေ့ ရပ်ခဲ့တဲ့နေရာကနေ စစေပါတယ်။
Class အသစ် TaskStore က စာကြည့်တိုက်မှူးလိုပါ။ tracker တစ်ခုလုံးကို ပေးလိုက်ရင် JSON document အဖြစ် သိမ်းပေးပြီး နောက်မှ document ကို ပြန်ယူကာ tracker ကို အရင်အတိုင်း ပြန်တည်ဆောက်ပေးပါတယ်။ Program ရဲ့ ကျန်တဲ့အပိုင်းက file ဘယ်မှာရှိလဲ၊ ဘာပုံစံလဲ ဆိုတာ ဘယ်တော့မှ မသိရပါဘူး။
Problem → Why → Solution
ပြဿနာ: ခြားထားတဲ့ စာကြောင်း format
List တစ်ခုကို သိမ်းဖို့ အမြန်ဆုံးနည်းက task တစ်ခုကို separator နဲ့ စာကြောင်းတစ်ကြောင်း ရေးတာပါ၊ "Buy milk|false" လိုမျိုးပါ။ Demo မှာ အလုပ်လုပ်ပေမယ့် တကယ့် data မှာ ပျက်ပါတယ်။ Separator ပါတဲ့ title ("Fix | login") ကို load လုပ်တဲ့အခါ field သုံးခု ခွဲထွက်သွားပါတယ်။ Value အားလုံးက String အဖြစ် ပြန်ရလို့ done က "false" ဆိုတဲ့ string ဖြစ်ပြီး Ruby မှာ အဲဒါက truthy ပါ၊ ဒါကြောင့် task တိုင်း ပြီးသွားသလို ပေါ်ပါတယ်။ File ထဲ တိုက်ရိုက်ရေးတာကြောင့် တစ်ဝက်မှာ crash ဖြစ်ရင် တစ်ဝက်တစ်ပျက် file ကျန်ပြီး နောက်တစ်ခါ start လုပ်တဲ့အခါ task တွေ ပျောက်သွားတာ ဒါမှမဟုတ် crash ဖြစ်တာ ဖြစ်ပါတယ်။
နောက်ထပ် ထောင်ချောက်တစ်ခုက id တွေမှာ ပုန်းနေပါတယ်။ သိမ်းထားတဲ့ file မှာ task တွေပဲ ပါရင် နောက် id ကို program က ခန့်မှန်းရပါတယ်။ အသစ်ဆုံး task ကို ဖျက်ပြီး restart လုပ်ရင် ခန့်မှန်းချက်က အဲဒီ id ကို ပြန်သုံးမိပြီး "task 4" လို့ ကိုးကားထားတဲ့ အဟောင်းတွေက တခြား task ကို ညွှန်သွားပါတယ်။
saved = "Buy milk|false"
title, done = saved.split("|")
puts "finished!" if done # prints: the String "false" is truthy
risky = "Fix | login bug|false"
p risky.split("|") # ["Fix ", " login bug", "false"] - three fieldsDelimiter format က ဘာကြောင့် မလုံလောက်တာလဲ
Delimiter format မှာ "ဒီ separator က data ရဲ့ အစိတ်အပိုင်းပါ" လို့ ပြောဖို့ နည်းလမ်း မရှိသလို type တွေကိုလည်း ဖျက်ပစ်ပါတယ်၊ အားလုံးက စာသားဖြစ်သွားပါတယ်။ JSON ကို ဒီအတွက်ပဲ ဒီဇိုင်းလုပ်ထားတာပါ။ String တွေက quote ခံပြီး escape လုပ်ထားတယ်၊ number နဲ့ boolean တွေက type မပျောက်ဘူး၊ ဖွဲ့စည်းပုံ (object တစ်ခုထဲမှာ object list) ကို ထင်ရှားစွာ ဖော်ပြတယ်။ Ruby ရဲ့ standard library မှာ JSON parser နဲ့ generator ပါပြီးသားမို့ ပြင်ဖို့ method call နှစ်ခုပဲ ကုန်ပါတယ်။
Core concept: object နဲ့ document ကြား ဘာသာပြန်တဲ့ store
သိမ်းတာဆိုတာ ဘာသာပြန်တာပါ။ Memory ထဲမှာ အပြုအမူပါတဲ့ Task object တွေ ရှိပြီး disk ပေါ်မှာတော့ စာသားပဲ ရှိပါတယ်။ TaskStore က နှစ်ခုကြားမှာ နေပြီး နှစ်ဖက်စလုံးကို ဘာသာပြန်ပါတယ်။ Valid file ဆိုတာ ဘာလဲဆိုတဲ့ စည်းမျဉ်းတွေကိုတော့ ပြန်ဝင်လာတဲ့လမ်းမှာ စစ်ပါတယ်၊ ဘာကြောင့်လဲဆိုတော့ file ဆိုတာ ကိုယ့် program က မနေ့က ရေးထားတာဖြစ်နေရင်တောင် program အပြင်ဘက်က input ဖြစ်လို့ပါ။
၁။ Document ပုံစံကို ရွေးပြီး ရေးချပါ
File က JSON object တစ်ခုတည်းပါ၊ key သုံးခုပါပါတယ်။ version (1၊ နောက်ကျတဲ့ format ကို မှတ်သားနိုင်ဖို့)၊ next_id (counter၊ id တွေ ပြန်မသုံးမိအောင်) နဲ့ tasks (id၊ title၊ priority၊ done ပါတဲ့ object list) ပါ။ Part 1 က Task#to_h က entry တစ်ခုကို ထုတ်ပေးပြီးသားဖြစ်ပြီး TaskTracker#to_h က အဲဒါတွေကို ထုပ်ပေးပါတယ်။
၂။ pretty_generate နဲ့ ထုတ်ပါ
JSON.pretty_generate(hash) က လူဖတ်လို့ရပြီး diff tool နဲ့ နှိုင်းယှဉ်လို့ရတဲ့ indent ပါတဲ့ စာသားကို ပြန်ပေးပါတယ်။ Quote နဲ့ မြန်မာစာလို ASCII မဟုတ်တဲ့ စာတွေအပါအဝင် string တွေကို မှန်ကန်စွာ escape လုပ်ပြီး မြန်မာစာကို UTF-8 စာလုံးအဖြစ် ရေးပါတယ်။
၃။ အတူတူပဲ validation ကို ဖြတ်ပြီး ပြန်တည်ဆောက်ပါ
Task.from_h နဲ့ TaskTracker.from_h က parse လုပ်ပြီးသား Hash ကို ဖတ်ပြီး ပုံမှန် constructor တွေကို ခေါ်ပါတယ်။ ဒါကြောင့် file ထဲက record တစ်ခုက task အသစ်တစ်ခု ဖြတ်ရတဲ့ စည်းမျဉ်းအတိုင်း ဖြတ်ရပါတယ်။ TaskTracker constructor က @next_id ကို သိမ်းထားတဲ့တန်ဖိုးနဲ့ အမြင့်ဆုံး id + 1 ထဲက ကြီးတာကို ယူလို့ လက်နဲ့ပြင်ထားတဲ့ file ကြောင့် id ထပ်တာ မဖြစ်နိုင်ပါဘူး။
၄။ ပျက်ကွက်မှုအားလုံးကို error class တစ်ခုထဲ ထုပ်ပါ
File မရှိတာက ပုံမှန်ပါ၊ ပထမဆုံး run မှာ tracker အလွတ်နဲ့ စပါတယ်။ File ပျက်စီးနေတာကတော့ ပုံမှန်မဟုတ်ပါဘူး။ TaskStore#load က JSON::ParserError နဲ့ ArgumentError ကို rescue လုပ်ပြီး file နာမည် (path အပြည့်အစုံမပါ) နဲ့ ပြဿနာကို ပြောပြတဲ့ message နဲ့ StoreError ကို raise လုပ်ပါတယ်။ Caller မှာ ကိုင်တွယ်ရမယ့် class တစ်ခုပဲရှိပြီး JSON library အတွင်းက stack trace ကို ဘယ်တော့မှ မမြင်ရပါဘူး။
၅။ Atomic စွာ ရေးပါ
save က tasks.json.tmp ကို အရင်ရေးပြီးမှ File.rename နဲ့ tasks.json ပေါ် ရွှေ့ပါတယ်။ စနစ်အများစုမှာ rename က အဟောင်း file ကို အဆင့်တစ်ဆင့်တည်းနဲ့ အစားထိုးပေးလို့ crash ဖြစ်ရင် အဟောင်းအပြည့်အစုံ ဒါမှမဟုတ် အသစ်အပြည့်အစုံ တစ်ခုခု ကျန်ပြီး နှစ်ခုရဲ့ တစ်ဝက်စီ မကျန်ပါဘူး။
၆။ အောင်မြင်တဲ့ ပြောင်းလဲမှုတိုင်းနောက် သိမ်းပါ
Cli က optional store တစ်ခု လက်ခံပြီး add၊ done နဲ့ delete ပြီးတိုင်း save ကို ခေါ်ပါတယ်။ ထွက်တဲ့အခါမှ သိမ်းရင် crash ဒါမှမဟုတ် Ctrl-C ဖြစ်တဲ့အခါ အားလုံး ပျောက်ပါမယ်။ ဒီလောက်အရွယ် list အတွက်တော့ ပြောင်းလဲမှုတိုင်းနောက် သိမ်းတာက မီလီစက္ကန့်အနည်းငယ်ပဲ ကုန်ပါတယ်။
| ပျက်ကွက်မှု | ဘယ်မှာ ဖမ်းလဲ | User မြင်ရတာ |
|---|---|---|
| File မရှိ | TaskStore#load (File.exist?) | Tracker အလွတ်၊ error မရှိ |
| JSON ပျက် | rescue JSON::ParserError | StoreError: tasks.json is not valid JSON |
| Record မှား (priority မသိ၊ title မပါ) | from_h ကနေ Task constructor | StoreError: tasks.json: task number 1: ... |
| Command မှားရိုက် | Cli ရဲ့ rescue | Error: ... reply၊ ဘာမှ မသိမ်း |
- Tracker ကို to_h နဲ့ Hash ပြောင်း
- Hash ကို pretty_generate နဲ့ JSON စာသား
- Temp file ရေးပြီး rename
- ပြန်ဖတ်: parse၊ validate၊ rebuild
File ထဲက အရာအားလုံးက task အသစ်တစ်ခု ဖြတ်ရတဲ့ constructor တွေကို ဖြတ်ပြီးမှ ယုံကြည်စရာ ဖြစ်ပါတယ်။
အခြေခံ ပုံစံ
def load(path)
return Collection.new unless File.exist?(path)
Collection.from_h(JSON.parse(File.read(path)))
end
def save(path, collection)
File.write("#{path}.tmp", JSON.pretty_generate(collection.to_h))
File.rename("#{path}.tmp", path)
endload က file မရှိရင် အလွတ် collection ပြန်ပြီး ရှိရင် parse လုပ်ကာ from_h နဲ့ ပြန်တည်ဆောက်ပါတယ်။ save က temp file ကို အရင်ရေးပြီး rename နဲ့ အစားထိုးပါတယ်။
Part 3 code: TaskStore နဲ့ သိမ်းပေးတဲ့ Cli
File က ပြည့်စုံပြန်ပါတယ်။ Part 3 က StoreError၊ Task.from_h၊ သိမ်းထားတဲ့ task တွေကို လက်ခံတဲ့ TaskTracker constructor၊ tracker ရဲ့ to_h နဲ့ from_h၊ TaskStore class နဲ့ Cli ရဲ့ store: option တို့ကို ထပ်ထည့်ပါတယ်။ Demo က အားလုံးကို Dir.mktmpdir ထဲမှာ run လို့ သင့် disk ပေါ်မှာ file မကျန်ပြီး output ထဲ path လည်း မပါပါဘူး။ Program run နှစ်ကြိမ်ကို အတုလုပ်ပြီး နောက်မှ file ကို တမင်ပျက်အောင် လုပ်ပြပါတယ်။
require "json"
require "tmpdir"
class TaskNotFound < StandardError
def initialize(id)
super("no task with id #{id}")
end
end
# New in Part 3: one error class for everything that can go wrong with the file.
class StoreError < StandardError; end
class Task
PRIORITIES = %i[low medium high].freeze
attr_reader :id, :title, :priority
def initialize(id:, title:, priority: :medium, done: false)
unless id.is_a?(Integer) && id.positive?
raise ArgumentError, "id must be a positive integer"
end
clean = title.to_s.strip
raise ArgumentError, "title can't be blank" if clean.empty?
unless PRIORITIES.include?(priority)
allowed = PRIORITIES.inspect
raise ArgumentError, "priority must be one of #{allowed}, got #{priority.inspect}"
end
raise ArgumentError, "done must be true or false" unless [true, false].include?(done)
@id = id
@title = clean
@priority = priority
@done = done
end
# New in Part 3: rebuild a Task from the Hash that JSON.parse produced.
def self.from_h(hash)
raise ArgumentError, "a task must be a JSON object" unless hash.is_a?(Hash)
new(id: hash["id"], title: hash["title"],
priority: hash["priority"].to_s.to_sym, done: hash["done"])
end
def done? = @done
def complete!
@done = true
self
end
def to_h
{ "id" => id, "title" => title, "priority" => priority.to_s, "done" => done? }
end
def to_s
"##{id} [#{done? ? "x" : " "}] #{title} (#{priority})"
end
end
class TaskTracker
include Enumerable
# New in Part 3: a tracker can start from tasks that were saved earlier.
def initialize(tasks: [], next_id: 1)
ids = tasks.map(&:id)
raise ArgumentError, "duplicate task ids" if ids.uniq.size != ids.size
@tasks = tasks.dup
@next_id = [next_id, (ids.max || 0) + 1].max
end
# New in Part 3: rebuild a tracker from the parsed document.
def self.from_h(data)
unless data.is_a?(Hash) && data["tasks"].is_a?(Array)
raise ArgumentError, 'expected an object with a "tasks" array'
end
tasks = data["tasks"].each_with_index.map do |record, index|
Task.from_h(record)
rescue ArgumentError => e
raise ArgumentError, "task number #{index + 1}: #{e.message}"
end
new(tasks: tasks, next_id: data["next_id"].is_a?(Integer) ? data["next_id"] : 1)
end
# New in Part 3: the document shape that goes into tasks.json.
def to_h
{ "version" => 1, "next_id" => @next_id, "tasks" => @tasks.map(&:to_h) }
end
def add(title, priority: :medium)
task = Task.new(id: @next_id, title: title, priority: priority)
@tasks << task
@next_id += 1
task
end
def each(&block)
return enum_for(:each) unless block
@tasks.each(&block)
self
end
def size = @tasks.size
def empty? = @tasks.empty?
def fetch(id)
@tasks.find { |task| task.id == id } || raise(TaskNotFound, id)
end
def complete(id) = fetch(id).complete!
def remove(id)
task = fetch(id)
@tasks.delete(task)
task
end
def pending = reject(&:done?)
end
# New in Part 3: all file handling lives here, behind load and save.
class TaskStore
def initialize(path)
@path = path
end
def load
return TaskTracker.new unless File.exist?(@path)
TaskTracker.from_h(JSON.parse(File.read(@path)))
rescue JSON::ParserError
raise StoreError, "#{File.basename(@path)} is not valid JSON"
rescue ArgumentError => e
raise StoreError, "#{File.basename(@path)}: #{e.message}"
end
def save(tracker)
temp = "#{@path}.tmp"
File.write(temp, JSON.pretty_generate(tracker.to_h))
File.rename(temp, @path)
end
end
class Cli
HELP = "commands: add <title> [!low|!medium|!high], list, done <id>, delete <id>"
CHANGING = %w[add done delete].freeze
# New in Part 3: an optional store that is saved after every successful change.
def initialize(tracker, store: nil)
@tracker = tracker
@store = store
end
def execute(line)
command, arg = line.strip.split(/\s+/, 2)
reply = case command
when "add" then add(arg)
when "list" then list
when "done" then "Completed #{@tracker.complete(parse_id(arg))}"
when "delete" then "Deleted #{@tracker.remove(parse_id(arg))}"
when nil then HELP
else "Unknown command #{command.inspect}. #{HELP}"
end
@store.save(@tracker) if @store && CHANGING.include?(command)
reply
rescue TaskNotFound, ArgumentError => e
"Error: #{e.message}"
end
private
def add(arg)
title, flag = arg.to_s.match(/\A(.*?)(?:\s+!(\w+))?\z/).captures
priority = flag ? flag.to_sym : :medium
"Added #{@tracker.add(title, priority: priority)}"
end
def list
return "No tasks yet." if @tracker.empty?
lines = @tracker.map(&:to_s)
lines << "#{@tracker.pending.size} of #{@tracker.size} pending"
lines.join("\n")
end
def parse_id(text)
id = Integer(text.to_s, 10, exception: false)
id || raise(ArgumentError, "expected a task id, got #{text.inspect}")
end
end
def session(title, cli, commands)
puts "== #{title} =="
commands.each do |command|
puts "> #{command}"
puts cli.execute(command)
end
end
# The demo works inside a temporary folder that is deleted when the block ends.
Dir.mktmpdir("task-tracker") do |dir|
path = File.join(dir, "tasks.json")
store = TaskStore.new(path)
session("first run (no file yet)", Cli.new(store.load, store: store), [
"add Buy milk !high",
"add မနက်ဖြန် အစည်းအဝေး",
"add Write tests !low",
"done 2",
"delete 3",
])
puts "-- tasks.json --"
puts File.read(path)
session("second run (loaded from disk)", Cli.new(store.load, store: store), [
"list",
"add Review notes",
])
File.write(path, '{"tasks": [')
begin
store.load
rescue StoreError => e
puts "== damaged file ==", "Error: #{e.message}"
end
bad = { "id" => 1, "title" => "Ship it", "priority" => "urgent", "done" => false }
File.write(path, JSON.generate({ "tasks" => [bad] }))
begin
store.load
rescue StoreError => e
puts "Error: #{e.message}"
end
endCode ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- A next id that can never go backwards
@next_id = [next_id, (ids.max || 0) + 1].maxသိမ်းထားတဲ့ next_id နဲ့ "အမြင့်ဆုံး id + 1" ထဲက ကြီးတာကို ယူပါတယ်။ File ထဲမှာ next_id က နိမ့်နေရင်တောင် (ids.max || 0) ကြောင့် task မရှိတဲ့အခါ 0 ကနေစပြီး 1 ရပါတယ်။
- Rebuild every record through Task
Task.from_h(record)Record တစ်ခုစီက Task.new ကို ဖြတ်လို့ priority မသိတာ၊ title မပါတာ၊ done က string ဖြစ်နေတာတွေကို ငြင်းပါတယ်။ Rescue က record နံပါတ်ကို message ထဲ ထည့်လို့ "task number 1: ..." လို့ ပေါ်တာပါ။
- Wrap parse failures
rescue JSON::ParserErrorJSON.parse က ပျက်တဲ့ text ကို JSON::ParserError နဲ့ ပယ်ပါတယ်။ ဒီ rescue က ကိုယ့် StoreError အဖြစ် ပြောင်းပြီး File.basename နဲ့ file နာမည်ပဲ ပြလို့ ကိုယ်ရေးထားတဲ့ message ထဲ path အပြည့်အစုံ မပါပါဘူး။
- Replace the file in one step
File.rename(temp, @path)temp file အပြည့်အစုံကို ရေးပြီးမှ rename လုပ်ပါတယ်။ ဒီ line မရောက်ခင် ပျက်သွားရင် tasks.json အဟောင်းက မထိမခိုက်ပဲ ရှိနေပါတယ်။
- Save only after success
@store.save(@tracker) if @store && CHANGING.include?(command)Command က raise လုပ်ရင် ဒီ line ကို မရောက်တော့လို့ မအောင်မြင်တဲ့ command က file ကို မထိပါဘူး။ list လို ဖတ်ယုံ command တွေကလည်း CHANGING ထဲ မပါလို့ မသိမ်းပါဘူး။
- A temporary folder for the demo
Dir.mktmpdir("task-tracker") do |dir|Block ပြီးတဲ့အခါ folder ကို အကြောင်းအရာနဲ့တကွ အလိုအလျောက် ဖျက်ပါတယ်။ Test တွေမှာ ကိုယ့် data file အစစ်ကို မထိဘဲ store ကို စမ်းလို့ရတဲ့ ပုံစံပါ။
- UTF-8 stays readable
puts File.read(path)Output ထဲက "မနက်ဖြန် အစည်းအဝေး" ကို ကြည့်ပါ၊ \u1019 လို escape sequence မဟုတ်ဘဲ မြန်မာစာအဖြစ် ဖတ်လို့ရပါတယ်။ Ruby ရဲ့ default encoding က UTF-8 ဖြစ်လို့ write နဲ့ read ကြားမှာ ဘာမှ ပျက်စီးမှု မရှိပါဘူး။
== first run (no file yet) ==
> add Buy milk !high
Added #1 [ ] Buy milk (high)
> add မနက်ဖြန် အစည်းအဝေး
Added #2 [ ] မနက်ဖြန် အစည်းအဝေး (medium)
> add Write tests !low
Added #3 [ ] Write tests (low)
> done 2
Completed #2 [x] မနက်ဖြန် အစည်းအဝေး (medium)
> delete 3
Deleted #3 [ ] Write tests (low)
-- tasks.json --
{
"version": 1,
"next_id": 4,
"tasks": [
{
"id": 1,
"title": "Buy milk",
"priority": "high",
"done": false
},
{
"id": 2,
"title": "မနက်ဖြန် အစည်းအဝေး",
"priority": "medium",
"done": true
}
]
}
== second run (loaded from disk) ==
> list
#1 [ ] Buy milk (high)
#2 [x] မနက်ဖြန် အစည်းအဝေး (medium)
1 of 2 pending
> add Review notes
Added #4 [ ] Review notes (medium)
== damaged file ==
Error: tasks.json is not valid JSON
Error: tasks.json: task number 1: priority must be one of [:low, :medium, :high], got :urgent- Cli က ပြောင်းလဲတဲ့ command ကို run
- Tracker က memory ထဲမှာ ပြောင်း
- store.save က JSON စာသား ဆောက်
- စာသားကို tasks.json.tmp ထဲ ရေး
- File.rename က tasks.json ကို အစားထိုး
Command အောင်မြင်
The file always holds a complete document
Command raise လုပ်
save is never reached, the file is untouched
JSON ကို ပြန်ဖတ်တဲ့အခါ symbol မဟုတ်ဘဲ string ပါ
JSON.parse က Hash ရဲ့ key တွေကို default အနေနဲ့ String အဖြစ် ပြန်ပေးပါတယ်၊ ဒါကြောင့် from_h က hash["id"] လို့ ရေးထားတာပါ။ symbolize_names: true option နဲ့ Symbol key ရအောင်လည်း လုပ်နိုင်ပါတယ်။ ပိုအရေးကြီးတဲ့ အချက်က Symbol value တွေ ပါပါတယ်။ JSON မှာ symbol ဆိုတာ မရှိလို့ :high ကို "high" လို့ ရေးပြီး ပြန်ဖတ်ရင် String "high" ရပါတယ်။ Task က priority ကို Symbol လို့ တောင်းဆိုတာကြောင့် from_h ထဲမှာ hash["priority"].to_s.to_sym လို့ ပြောင်းပေးရတာပါ။
require "json"
text = '{"id": 1, "done": false, "title": null}'
data = JSON.parse(text)
p data # keys come back as Strings
p data["done"], data["title"] # real false and nil, not text
p JSON.parse(text, symbolize_names: true) # an option when you prefer Symbol keys
puts JSON.generate({ id: 1, priority: :high }) # a Symbol is written as a String
p JSON.parse(JSON.generate({ priority: :high }))["priority"]Boolean နဲ့ null တို့က အရောင်းအဝယ်မရှိ အတိအကျ ပြန်ရပါတယ်။ false က false၊ null က nil ပါ။ ဒီအချက်က pipe format ကို ပယ်ချရတဲ့ အဓိကအကြောင်းရင်းပါ။ Hash ကို Ruby 4.0.9 ရဲ့ print format နဲ့ ပြထားတာဖြစ်လို့ Ruby 3.3 နဲ့ ယခင်ဗားရှင်းတွေမှာ {"id"=>1} လို ပေါ်ပါလိမ့်မယ်။
JSON file ရဲ့ ကန့်သတ်ချက်များ
JSON file တစ်ခုက personal tool တစ်ခုအတွက် ကောင်းမွန်ပါတယ်၊ ဒါပေမယ့် ကန့်သတ်ချက်တွေ ရှိပါတယ်။ Tracker နှစ်ခု တစ်ပြိုင်နက် run ပြီး တစ်ခုက တစ်ခုရဲ့ ပြောင်းလဲမှုကို မသိဘဲ ဖိရေးရင် နောက်ဆုံးရေးတဲ့သူ အနိုင်ရပါတယ်။ Save တိုင်းက list တစ်ခုလုံးကို ပြန်ရေးလို့ task ထောင်ပေါင်းများစွာမှာ နှေးလာပါလိမ့်မယ်။ History ဆိုတာလည်း မရှိပါဘူး။ File#flock လို advisory lock တွေ ရှိပေမယ့် အဲဒီအဆင့်ရောက်ရင် SQLite လို database က ပိုကောင်းတဲ့ tool ဖြစ်လေ့ရှိပါတယ်။ TaskStore ရဲ့ load နဲ့ save interface ကိုတော့ ဆက်ထားနိုင်ပြီး အတွင်းပိုင်းပဲ ပြောင်းရမှာပါ။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Config file၊ editor setting၊ package manifest (package.json၊ Gemfile.lock)၊ သိမ်းထားတဲ့ game state နဲ့ todo manager လို CLI tool သေးသေးလေးတွေ အားလုံးက ဒီပုံစံအတိုင်း သုံးပါတယ်။ Version ပါတဲ့ JSON document ကို startup မှာ load လုပ်ပြီး ပြောင်းလဲမှုတစ်ခုနောက် save လုပ်ပါတယ်။ version field ကြောင့် နောက်ထွက်မယ့် release က "ဒါက version 1 file ပါ၊ မသုံးခင် convert လုပ်ပါ" လို့ ပြောနိုင်ပါတယ်။ next_id က database sequence နဲ့ အတူတူပါပဲ၊ row တွေ ဖျက်ပြီးရင် counter ကို ပြန်တွက်လို့ မရတော့လို့ သိမ်းထားရတာပါ။
Atomic အစားထိုးတာက လက်တွေ့ tool တွေမှာ အရေးကြီးပါတယ်။ Editor တွေနဲ့ package manager တွေက temp file ရေးပြီး rename လုပ်ကြပါတယ်၊ ဘာကြောင့်လဲဆိုတော့ user တွေက Ctrl-C နှိပ်ကြပြီး စက်တွေက မီးပျက်လို့ပါ။ Process တစ်ခုထက်ပိုပြီး ပြင်တဲ့ ဒါမှမဟုတ် ကြီးထွားလာတဲ့ data အတွက် နောက်အဆင့်က SQLite လို database ဖြစ်ပြီး transaction နဲ့ lock ရပါတယ်။ TaskStore ရဲ့ interface (load နဲ့ save) ကို ထိန်းထားနိုင်ပြီး အတွင်းပိုင်းပဲ ပြောင်းရပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
ကိုယ့် program ရေးထားလို့ file ကို ယုံတာ
User တွေက file ကို ပြင်ကြတယ်၊ ဗားရှင်းအဟောင်းတွေက ပုံစံမတူတာ ရေးထားတတ်တယ်၊ disk တွေလည်း ပျက်စီးနိုင်တယ်။ ဒါကြောင့် load ကို မှားတဲ့ input အဖြစ် ဆက်ဆံပြီး ပုံမှန် constructor တွေကို ဖြတ်စေပါ။ Validation မလုပ်ရင် priority "urgent" ပါတဲ့ record တစ်ခုက ကျန်တဲ့ program တစ်ခုလုံးထဲ ပျံ့နှံ့သွားပါလိမ့်မယ်။
File ကို တိုက်ရိုက် ထပ်ရေးတာ
File.write(path, ...) က file ကို ဖွင့်လိုက်တာနဲ့ အဟောင်းကို ဖျက်ပစ်ပါတယ်။ ရေးနေရင်းနဲ့ process ပျက်သွား ဒါမှမဟုတ် Ctrl-C နှိပ်ရင် တစ်ဝက်တစ်ပျက် file ပဲ ကျန်ပြီး ပြန်ယူလို့ မရတော့ပါဘူး။ temp file ကို ရေးပြီး File.rename နဲ့ အစားထိုးပါ။
ပျက်စီးနေတဲ့ file ကို တိတ်တိတ် အလွတ်နဲ့ အစားထိုးတာ
rescue လုပ်ပြီး TaskTracker.new ပြန်ပေးလိုက်ရင် program က ပုံမှန်အတိုင်း စလည်ပါတယ်၊ ဒါပေမယ့် user ရဲ့ ပထမ add ရဲ့ save က ပြန်ယူလို့ရနိုင်ခဲ့တဲ့ ပျက်စီးနေတဲ့ file ကို task တစ်ခုပဲ ပါတဲ့ file နဲ့ ထပ်ရေးသွားပါတယ်။ StoreError ကို raise လုပ်ပြီး user ကို ဆုံးဖြတ်ခွင့် ပေးပါ။
JSON က symbol တွေကို string ပြောင်းတာ မေ့တာ
priority: :high ကို သိမ်းပြီး ပြန်ဖတ်ရင် String "high" ရပါတယ်၊ Task က Symbol ပဲ လက်ခံလို့ Task.new က ငြင်းပါတယ်။ from_h ထဲမှာ ပြောင်းပေးရပါမယ်။ ဒါမှမဟုတ် သိမ်းထားတဲ့ file တိုင်းက priority နဲ့ "high" အကြောင်း message ပေးပြီး load မဖြစ်တော့ပါဘူး။
Mini challenge
File format နှစ်မျိုးလုံးကို ဖတ်ပါ
Tracker ရဲ့ version 0 က task Hash တွေပါတဲ့ bare JSON array ကိုပဲ version၊ next_id မပါဘဲ သိမ်းခဲ့တယ်လို့ ယူဆပါ။ load_snapshot(path) ကို ရေးပါ။ File နှစ်မျိုးလုံးအတွက် version 1 shape ရှိတဲ့ Hash ကို ပြန်ပေးရမယ်။ Array အတွက် wrap လုပ်ပြီး next_id ကို အမြင့်ဆုံး id + 1 (list အလွတ်ဆိုရင် 1) အဖြစ် တွက်ပါ။ File မရှိရင် snapshot အလွတ်ပြန်ပါ။ Array မဟုတ်ဘဲ tasks array ပါတဲ့ object လည်း မဟုတ်ရင် StoreError ကို raise လုပ်ပါ။
- File မရှိရင် {"version" => 1, "next_id" => 1, "tasks" => []} ပြန်ပါ
- Bare array ကို wrap လုပ်ပြီး next_id ကို အမြင့်ဆုံး id + 1 (array အလွတ်ဆို 1) ထားပါ
- Object က ကိုယ်ပိုင် next_id ကို ထိန်းထားပေမယ့် အမြင့်ဆုံး id + 1 ထက် ဘယ်တော့မှ မနိမ့်စေနဲ့
- မမှန်တဲ့ JSON ဒါမှမဟုတ် တခြား shape ရှိတဲ့ JSON အတွက် message ပါတဲ့ StoreError ကို raise လုပ်ပါ
require "json"
class StoreError < StandardError; end
def load_snapshot(path)
# TODO: a missing file returns an empty version-1 snapshot
# TODO: parse the JSON and wrap JSON::ParserError in a StoreError
# TODO: a bare Array is a version-0 file: wrap it as { "tasks" => array }
# TODO: the result needs a "tasks" Array of Hashes, otherwise raise StoreError
# TODO: next_id is never lower than the highest id + 1
endရလဒ်: File အမျိုးအစား ခုနစ်ခုအတွက် line တစ်ကြောင်းစီ ထွက်ပါမယ်။ missing နဲ့ ဗလာ array အတွက် next_id=1၊ v0.json အတွက် next_id=8၊ v1-low အတွက် 6၊ v1-high အတွက် 40၊ broken.json နဲ့ number.json အတွက် StoreError message တစ်ခုစီပါ။
အရိပ်အမြွက် ကြည့်ရန်
File.exist? နဲ့ အရင်စစ်ပါ။ Id တွေကို filter_map နဲ့ ထုတ်ပြီး Integer မဟုတ်တာတွေကို ကျော်ပါ။ [saved, highest + 1].max က next_id မနိမ့်အောင် ထိန်းပေးပါတယ်။ Method တစ်ခုလုံးရဲ့ နောက်ဆုံးမှာ rescue JSON::ParserError ထည့်လို့ရပါတယ်။
အဖြေ ကြည့်ရန်
require "json"
require "tmpdir"
class StoreError < StandardError; end
# Reads a version-0 file (a bare Array) or a version-1 file (an object) and
# always returns the version-1 shape.
def load_snapshot(path)
return { "version" => 1, "next_id" => 1, "tasks" => [] } unless File.exist?(path)
data = JSON.parse(File.read(path))
data = { "tasks" => data } if data.is_a?(Array)
unless data.is_a?(Hash) && data["tasks"].is_a?(Array) && data["tasks"].all?(Hash)
raise StoreError, "#{File.basename(path)} has an unknown shape"
end
ids = data["tasks"].filter_map { |task| task["id"] if task["id"].is_a?(Integer) }
saved = data["next_id"].is_a?(Integer) ? data["next_id"] : 1
next_id = [saved, (ids.max || 0) + 1].max
{ "version" => 1, "next_id" => next_id, "tasks" => data["tasks"] }
rescue JSON::ParserError
raise StoreError, "#{File.basename(path)} is not valid JSON"
end
cases = {
"missing.json" => nil,
"v0-empty.json" => "[]",
"v0.json" => '[{"id": 3, "title": "Old task"}, {"id": 7, "title": "Older task"}]',
"v1-low.json" => '{"version": 1, "next_id": 2, "tasks": [{"id": 5}]}',
"v1-high.json" => '{"version": 1, "next_id": 40, "tasks": [{"id": 5}]}',
"broken.json" => '{"tasks": [',
"number.json" => "42",
}
Dir.mktmpdir("snapshots") do |dir|
cases.each do |name, content|
path = File.join(dir, name)
File.write(path, content) if content
begin
snapshot = load_snapshot(path)
puts "#{name}: next_id=#{snapshot["next_id"]} tasks=#{snapshot["tasks"].size}"
rescue StoreError => e
puts "#{name}: StoreError - #{e.message}"
end
end
endQuick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Delimiter format က separator ပါတဲ့ title တွေမှာ ပျက်ပြီး type တွေ ဆုံးရှုံးလို့ version ပါတဲ့ JSON document ကို သုံးပါ
- TaskStore က load/save ကို တစ်နေရာတည်းမှာ ထားပြီး model နဲ့ Cli က path ကို မသိစေပါဘူး
- File ထဲက data ကို ယုံကြည်စရာမရှိတဲ့ input အဖြစ် ဆက်ဆံပြီး ပုံမှန် constructor တွေ ဖြတ်စေကာ StoreError အဖြစ် ထုတ်ပြောပါ
- Temp file ရေးပြီး File.rename နဲ့ အစားထိုးတာက crash မှာ file တစ်ဝက်တစ်ပျက် မကျန်စေပါဘူး
- next_id ကို သိမ်းပြီး load တဲ့အခါ အမြင့်ဆုံး id + 1 ထက် မနိမ့်စေလို့ id ပြန်မသုံးမိပါဘူး
Official Ruby Documentation — Ruby Documentation