Thuta Learning
Ruby
AdvancedProgrammingအခြေခံ

Next Steps

Rubyသင်ခန်းစာ 2945 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Course ထဲက class၊ module၊ block၊ exception၊ JSON တွေက program တစ်ခုထဲမှာ ဘယ်လို ဆက်စပ်လဲ မြင်နိုင်ဖို့
  • each ကို define လုပ်ပြီး Enumerable ကို include လုပ်ကာ ကိုယ်ပိုင် collection class တစ်ခု ရေးနိုင်ဖို့
  • Test framework မပါဘဲ lambda နဲ့ closure သုံးပြီး program ရဲ့ ကိုယ်ပိုင် self-check ရေးနိုင်ဖို့
  • လမ်းကြောင်းလေးခုထဲက ကိုယ့်ရည်မှန်းချက်နဲ့ ကိုက်တာကို ရွေးပြီး project သေးသေးတစ်ခုနဲ့ စနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Ruby ရဲ့ အခြေခံအပိုင်းတွေ အားလုံးကို အခု တွေ့ပြီးပါပြီ၊ variable၊ method၊ array နဲ့ hash၊ block၊ class နဲ့ module၊ exception၊ file၊ gem နဲ့ test တို့ပါ။ ကိရိယာအစုံ ပိုင်ဆိုင်တာက မီးဖိုချောင်မှာ ဓားနဲ့ အိုးတွေ ပြည့်စုံတာနဲ့ တူပါတယ်။ ဟင်းတစ်ခွက် ချက်ကြည့်မှ အဲဒါတွေ အတူ ဘယ်လို အလုပ်လုပ်လဲ သင်ယူရပါတယ်။

ဒါကြောင့် နောက်ဆက်လုပ်သင့်တာက tutorial တစ်ခု ထပ်လိုက်တာ မဟုတ်ဘဲ project သေးသေးလေးတစ်ခု ဆောက်တာပါ။ ဒီ lesson က အဲဒီလို project တစ်ခုရဲ့ ပုံစံကို ပြပြီး နောက်ဆက်လေ့လာနိုင်တဲ့ လမ်းကြောင်းတွေကို ညွှန်ပြပေးမှာပါ။

Problem → Why → Solution

ပြဿနာ: ဖိုင်အလွတ်ရှေ့မှာ ခက်ခဲနေတာ

Course ပြီးတဲ့နောက် အဖြစ်များတဲ့ ထောင်ချောက်က tutorial ကူးခုန်တာပါ။ Example တိုင်းကို လိုက်လုပ်နိုင်ပေမယ့် ဖိုင်အလွတ်ကို မြင်ရင် ဘာကနေ စရမလဲ မသိတော့ပါဘူး။ ဗဟုသုတက သီးခြားသေတ္တာတွေထဲမှာ ရှိနေလို့ပါ၊ hash အတွက် lesson တစ်ခု၊ exception အတွက် တစ်ခု၊ JSON အတွက် တစ်ခု။ တကယ့် feature တစ်ခုကတော့ အဲဒါအားလုံးကို နေရာတစ်ခုတည်းမှာ အစီအစဉ်မှန်မှန် လိုပါတယ်။

ပေါင်းစပ်ဖို့ လေ့ကျင့်မထားရင် code က parse လုပ်တာ၊ စစ်တာ၊ ပေါင်းတာ၊ print ထုတ်တာတွေ ရောနေတဲ့ script ရှည်တစ်ခု ဖြစ်သွားပါတယ်။ အောက်ကလိုပါပဲ။ ဖြေရှင်းနည်းက တာဝန်တစ်ခုစီ ဘယ်နေရာမှာ နေမလဲ ကိုယ်တိုင်ဆုံးဖြတ်ရတဲ့ project သေးသေးတစ်ခု လုပ်ကြည့်တာပါ။

tangled_import.rb
# Parsing, checking, adding up and printing tangled together
total = 0
File.readlines("expenses.csv").each do |line|    # Errno::ENOENT if the file is missing
  title, amount, category = line.split(",")
  next if amount.to_f <= 0                       # "n/a".to_f is 0.0: silently skipped
  total += amount.to_f                           # money as floats
  puts "#{title}: #{amount} (#{category})"       # category still has its newline
end
puts total

ဘာကြောင့် သင်ခန်းစာတွေက မလုံလောက်တာလဲ

Lesson တစ်ခုစီက tool တစ်ခုကို သီးသန့် ပြပါတယ်။ ဒါပေမယ့် tool တွေကြား ဆက်ကြောင်း (seam) တွေကို မပြပါဘူး၊ raw input က validated object ဖြစ်လာတဲ့နေရာ၊ error တစ်ခုကို ဖမ်းတဲ့နေရာ၊ ရလဒ်ကို မပုံနှိပ်ခင် တွက်တဲ့နေရာတွေပါ။ အဲဒီ seam တွေကို ရွေးချယ်တာက project ရဲ့ အဓိကအလုပ်ပါ။

Core concept: လုပ်ငန်းတစ်ခုကို အလွှာတစ်ခု

အောက်က capstone က ဒီ course ထဲက အရာအားလုံးနီးပါးကို program တစ်ခုထဲမှာ သုံးထားလို့ အပိုင်းတွေ ဘယ်လို ကိုက်ညီလဲ မြင်ဖို့ အကောင်းဆုံးပါ။ Expense importer တစ်ခုက CSV ကနေ ရမယ့် စာတန်းတွေလို raw row တွေကို လက်ခံပါတယ်။ Row တစ်ခုစီက စစ်ဆေးပြီးသား Expense object ဖြစ်လာတယ်၊ ဒါမှမဟုတ် အကြောင်းရင်းနဲ့အတူ ပယ်ချခံရပါတယ်။ လက်ခံထားတဲ့ expense တွေကို Ledger ထဲ သိမ်းပြီး mixin တစ်ခုနဲ့ အနှစ်ချုပ်ကာ JSON အဖြစ် သိမ်းပြီး ပြန်ဖတ်ပါတယ်။ နောက်ဆုံး program က ကိုယ့်ရလဒ်ကို ကိုယ်တိုင် စစ်ပါတယ်။

တာဝန်ခွဲဝေပုံကို သတိထားပါ။ Expense က valid expense ဆိုတာ ဘာလဲ သိပြီး row က စည်းမျဉ်းကို ချိုးဖောက်ရင် ValidationError ကို raise လုပ်ပါတယ်။ Ledger က expense တွေကို သိမ်းပြီး လိုက်ပတ်ရုံပဲ လုပ်ပါတယ်၊ each ကို define လုပ်ပြီး Enumerable ကို include လုပ်ထားလို့ map၊ group_by၊ sum၊ max_by တွေကို အလကား ရပါတယ်။ Summarizable module က cents နဲ့ category ရှိတဲ့ object တွေကို ကိုင်ထားတဲ့ Enumerable ကို ဒီ domain ရဲ့ အသိပညာ (စုစုပေါင်း၊ category အလိုက် စုစုပေါင်း) ထပ်ထည့်ပေးပါတယ်။ အပိုင်းတစ်ခုစီကို ကျန်တာ မဖွင့်ဘဲ ဖတ်၊ ပြင်၊ test လုပ်လို့ ရပါတယ်။

ကူးယူသင့်တဲ့ အချက် နှစ်ခု ရှိပါတယ်။ ပိုက်ဆံကို float မဟုတ်ဘဲ integer cent နဲ့ သိမ်းထားလို့ စုစုပေါင်းတွေက တိတိကျကျ ကိုက်ပါတယ်။ Import loop က row တစ်ခုစီမှာ ValidationError ကို ဖမ်းလို့ မှားတဲ့ row တစ်ခုက import တစ်ခုလုံးကို မရပ်ပါဘူး၊ ပယ်ချတာတိုင်းလည်း အကြောင်းရင်း ကျန်ပါတယ်။ နောက်ဆုံး self-check က ကိုယ်ကိုင်ထားတဲ့ variable ထဲ အောင်တဲ့အရေအတွက်ကို ထည့်တဲ့ lambda ကို သုံးထားလို့ Procs, lambdas and closures lesson နဲ့ ဆက်စပ်ပါတယ်။

Course topicCapstone ထဲမှာ ပေါ်တဲ့နေရာ
Class နဲ့ objectExpense၊ Ledger
Module နဲ့ mixinLedger ထဲ include လုပ်တဲ့ Summarizable
Block နဲ့ iteratorLedger#each၊ each_with_index၊ group_by၊ sum(&:cents)
Lambda နဲ့ closuremoney formatter နဲ့ အောင်တဲ့ check ကို ရေတွက်တဲ့ check lambda
ExceptionRow တစ်ခုစီမှာ raise နဲ့ rescue လုပ်တဲ့ ValidationError
File နဲ့ JSONDir.mktmpdir ထဲက save နဲ့ load
Mental model: raw row ဝင်၊ report ထွက်
  1. Raw row တွေက ရိုးရိုး hash အဖြစ် ဝင်
  2. Expense က လက်ခံ ဒါမှမဟုတ် raise
  3. Ledger က သိမ်း၊ Enumerable က ပတ်
  4. Report နဲ့ self-check က ပိတ်

အပိုင်းတစ်ခုစီက ကိုယ့်အလုပ်ကိုပဲ လုပ်ပါတယ်။ Report မှားနေရင် ဘယ်အပိုင်းကို ဖွင့်ကြည့်ရမလဲ ချက်ချင်း သိပါတယ်။

အခြေခံ ပုံစံ

ruby
class Collection
  include Enumerable          # needs each; gives map, select, sum, max_by, ...

  def each(&block)
    return enum_for(:each) unless block   # no block given: return an Enumerator

    @items.each(&block)
    self
  end
end

ကိုယ်ပိုင် collection class တစ်ခုက each ကို define လုပ်ပြီး Enumerable ကို include လုပ်ရင် map၊ select၊ sum စတဲ့ method အားလုံး အလိုအလျောက် ရပါတယ်။ Block မပါရင် enum_for(:each) နဲ့ Enumerator ပြန်ပေးလို့ each_with_index လို chain တွေလည်း အလုပ်လုပ်ပါတယ်။

Capstone: အသုံးစရိတ် import နဲ့ report

ဒီ file တစ်ခုတည်းမှာ course ရဲ့ အဓိကအပိုင်းတွေ ပါပါတယ်။ ကြိုရေးထားတဲ့ raw row ရှစ်ကြောင်း (လေးကြောင်းက မှားနေတယ်) ကို Expense အဖြစ် ပြောင်းပြီး category အလိုက် စုစုပေါင်းနဲ့ အကြီးဆုံး အသုံးစရိတ်ကို ရိုက်ထုတ်ပါတယ်။ ပိုက်ဆံကို cent (integer) နဲ့ သိမ်းထားတာကို သတိပြုပါ။ ပယ်ချခံရတဲ့ row တွေကို အကြောင်းရင်းနဲ့ စာရင်းပြုထားပြီး JSON အဖြစ် temp folder ထဲ သိမ်းကာ ပြန်ဖတ်ပါတယ်။ နောက်ဆုံးမှာ self-check အောင်တာ အရေအတွက်ကို ပြပါတယ်။

capstone.rb
require "json"
require "tmpdir"

class ValidationError < StandardError; end

module Summarizable
  def total_cents = sum(&:cents)

  def totals_by_category
    group_by(&:category).transform_values { |expenses| expenses.sum(&:cents) }
  end
end

class Expense
  CATEGORIES = %w[food transport fun].freeze

  attr_reader :title, :cents, :category

  def self.from_row(row)
    new(
      title: row[:title].to_s,
      cents: (parse_amount(row[:amount]) * 100).round,
      category: row[:category].to_s.downcase
    )
  end

  def self.parse_amount(text)
    Float(text)
  rescue ArgumentError, TypeError
    raise ValidationError, "amount is not a number"
  end

  def initialize(title:, cents:, category:)
    raise ValidationError, "title is required" if title.strip.empty?
    raise ValidationError, "amount must be positive" unless cents.positive?
    unless CATEGORIES.include?(category)
      raise ValidationError, "unknown category '#{category}'"
    end

    @title = title.strip
    @cents = cents
    @category = category
  end

  def to_h = { title: title, cents: cents, category: category }
end

class Ledger
  include Enumerable
  include Summarizable

  def initialize(expenses = [])
    @expenses = expenses
  end

  def <<(expense)
    @expenses << expense
    self
  end

  def each(&block)
    return enum_for(:each) unless block

    @expenses.each(&block)
    self
  end

  def to_json_text = JSON.pretty_generate(map(&:to_h))

  def self.from_json_text(text)
    rows = JSON.parse(text, symbolize_names: true)
    new(rows.map { |attributes| Expense.new(**attributes) })
  end
end

def import(rows)
  ledger = Ledger.new
  rejected = []
  rows.each_with_index do |row, index|
    ledger << Expense.from_row(row)
  rescue ValidationError => error
    rejected << "row #{index + 1}: #{error.message}"
  end
  [ledger, rejected]
end

rows = [
  { title: "Lunch", amount: "4.50", category: "food" },
  { title: "Bus pass", amount: "30", category: "Transport" },
  { title: "Cinema", amount: "12.25", category: "fun" },
  { title: "Dinner", amount: "18.40", category: "food" },
  { title: "", amount: "5", category: "food" },
  { title: "Mystery", amount: "n/a", category: "fun" },
  { title: "Gift", amount: "20", category: "gifts" },
  { title: "Refund", amount: "-3", category: "food" }
]

ledger, rejected = import(rows)
money = ->(cents) { format("%.2f", cents / 100.0) }

puts "Imported #{ledger.count} of #{rows.size} rows"
ledger.totals_by_category.sort.each do |category, cents|
  puts "  #{category.ljust(10)} #{money.call(cents).rjust(7)}"
end
biggest = ledger.max_by(&:cents)
puts "Total: #{money.call(ledger.total_cents)} (largest: #{biggest.title})"
puts "Rejected:"
rejected.each { |reason| puts "  #{reason}" }

reloaded = nil
Dir.mktmpdir("ledger") do |dir|
  path = File.join(dir, "ledger.json")
  File.write(path, ledger.to_json_text)
  reloaded = Ledger.from_json_text(File.read(path))
end

checks = 0
check = lambda do |label, condition|
  raise "self-check failed: #{label}" unless condition

  checks += 1
end

bad_amount_raises = begin
  Expense.from_row(title: "x", amount: "abc", category: "fun")
  false
rescue ValidationError
  true
end

sums_match = ledger.totals_by_category.values.sum == ledger.total_cents
check.call("four rows imported", ledger.count == 4)
check.call("four rows rejected", rejected.size == 4)
check.call("categories add up to the total", sums_match)
check.call("JSON round trip keeps every row", reloaded.map(&:to_h) == ledger.map(&:to_h))
check.call("JSON round trip keeps the total", reloaded.total_cents == 6515)
check.call("a bad amount raises ValidationError", bad_amount_raises)
puts "#{checks} self-checks passed"

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Mixindef total_cents = sum(&:cents)

    Summarizable က sum ကို ဘယ်ကရလဲ မသိပါဘူး၊ Enumerable ကို include လုပ်ထားတဲ့ class ထဲမှာပဲ အလုပ်လုပ်မယ်လို့ ယူဆထားတာပါ။ ဒါကြောင့် Ledger မှာ include Enumerable နဲ့ include Summarizable နှစ်ခုလုံး လိုပါတယ်။

  2. Validationraise ValidationError, "amount is not a number"

    Float("n/a") က ဆက်စပ်မှုမရှိတဲ့ ArgumentError ပေးတာကို parse_amount က ဖမ်းပြီး လုပ်ငန်းနယ်ပယ်ရဲ့ ValidationError အဖြစ် ပြောင်းပါတယ်။ rescue က ဒီ method တစ်ခုထဲမှာပဲ ရှိလို့ တခြား bug တွေကို မဖုံးပါဘူး။

  3. Enumerableinclude Enumerable

    Ledger က each ကိုပဲ define လုပ်ထားပေမယ့် count၊ map၊ max_by၊ group_by တွေကို အားလုံး သုံးလို့ ရပါတယ်။ ledger.count က 4 ပြန်ပြီး ledger.max_by(&:cents) က Bus pass ကို ရွေးပါတယ်။

  4. Per-row rescuerescue ValidationError => error

    ဒီ rescue က each_with_index ရဲ့ block တစ်ခုချင်းစီကို ကာကွယ်တာမို့ row 5 မှာ error တက်ရင် row 5 ကိုပဲ ကျော်ပြီး row 6 က ဆက်လုပ်ပါတယ်။ ပယ်ချတဲ့ အကြောင်းရင်းကို rejected ထဲ စုထားပါတယ်။

  5. JSON loadnew(rows.map { |attributes| Expense.new(**attributes) })

    ပြန်ဖတ်တဲ့ row တစ်ခုစီ (symbolize_names ကြောင့် symbol key hash) ကို ** နဲ့ keyword argument အဖြစ် ပြန်ဖြန့်ပြီး Expense.new ကိုပဲ ထပ်ခေါ်ပါတယ်။ ဒါကြောင့် ဖိုင်ထဲက ဒေတာကိုလည်း တူညီတဲ့ validation က စစ်ပါတယ်။

  6. Closure countercheck = lambda do |label, condition|

    check lambda က အပြင်က checks variable ကို ကိုင်ထားပြီး အောင်တိုင်း 1 တိုးပါတယ်။ စစ်ချက်တစ်ခု မအောင်ရင် raise လုပ်လို့ program က ချက်ချင်း ရပ်ပြီး ဘယ်စစ်ချက် မှားလဲ ပြောပါတယ်။

You should see
Imported 4 of 8 rows
  food         22.90
  fun          12.25
  transport    30.00
Total: 65.15 (largest: Bus pass)
Rejected:
  row 5: title is required
  row 6: amount is not a number
  row 7: unknown category 'gifts'
  row 8: amount must be positive
6 self-checks passed

လမ်းကြောင်းလေးခု

Ruby ကို ဆက်လေ့လာဖို့ လမ်းကြောင်းတစ်ခုတည်း မရှိပါဘူး။ ကိုယ့်ရည်မှန်းချက်ကို အရင်ရွေးပါ၊ ဥပမာ website ဆောက်ချင်လား၊ အလုပ်တွေကို automate လုပ်ချင်လား၊ ဘာသာစကားကို ပိုနက်နက်ရှိုင်းရှိုင်း သိချင်လား။ လမ်းကြောင်းတစ်ခုစီမှာ project သေးသေးတစ်ခုနဲ့ စပါ။ ဒီ capstone ကိုပဲ အခြေခံအဖြစ် သုံးလို့ ရပါတယ်။

လမ်းကြောင်းလေ့လာရမယ့်အရာပထမ project
ဘာသာစကား နက်ရှိုင်းမှုComparable၊ Struct နဲ့ Data၊ pattern matching၊ lazy enumeratorData နဲ့ case/in သုံးတဲ့ စာသား စာရင်းအင်း script
အရည်အသွေး toolMinitest ဒါမှမဟုတ် RSpec၊ RuboCop၊ Rake၊ BundlerCapstone ကို test နဲ့ Rakefile ထည့်ခြင်း
WebRack၊ Sinatra၊ ပြီးတော့ RailsLedger ကို ပြတဲ့ web page သေးသေးတစ်ခု
AutomationOptionParser၊ File နဲ့ Dir၊ အချိန်ကာလအလိုက် run တဲ့ scriptCSV path ကို ယူတဲ့ command-line importer

နောက်ထပ် feature သုံးခုကို အနည်းငယ် စမ်းကြည့်ခြင်း

အောက်က script မှာ ဒီ course မှာ မပါခဲ့တဲ့ ဒါပေမယ့် ခေတ်သစ် Ruby code တွေမှာ အမြဲတွေ့ရတဲ့ feature သုံးခု ပါပါတယ်။ Comparable က <=> ကို define လုပ်ရုံနဲ့ >၊ <၊ min၊ sort တွေ ပေးပါတယ်။ case/in က hash နဲ့ array ကို ပုံစံနဲ့ ယှဉ်ပြီး အပိုင်းတွေကို variable ထဲ ထုတ်ပေးပါတယ်။ Data.define က မပြောင်းလဲနိုင်တဲ့ value object တစ်ခုကို အတိုချုပ် ဆောက်ပေးပါတယ်။

taste.rb
class Version
  include Comparable

  attr_reader :parts

  def initialize(text) = @parts = text.split(".").map(&:to_i)
  def <=>(other) = parts <=> other.parts
  def to_s = parts.join(".")
end

puts Version.new("1.10.0") > Version.new("1.9.9")          # true
puts [Version.new("2.0.0"), Version.new("1.4.2")].min      # 1.4.2

response = { status: "ok", items: [1, 2, 3] }
message = case response
          in { status: "ok", items: [first, *rest] }
            "first=#{first}, rest=#{rest}"
          in { status: "error" }
            "failed"
          end
puts message                                               # first=1, rest=[2, 3]

Coord = Data.define(:lat, :lng)
spot = Coord.new(lat: 16.8, lng: 96.2)
p spot                                # #<data Coord lat=16.8, lng=96.2>
p spot.with(lat: 17.0)                # #<data Coord lat=17.0, lng=96.2>
puts spot.frozen?                     # true

ဆက်လေ့လာဖို့ အလေ့အကျင့်

၁။ ကိုယ်တကယ် သုံးမယ့် အရာတစ်ခု ရွေး

ကိုယ့် စရိတ်၊ ကြည့်ချင်တဲ့ ရုပ်ရှင်စာရင်း၊ file အမည်ပြောင်းတာလို ကိုယ့်ဘဝနဲ့ ဆိုင်တဲ့ ပြဿနာက စိတ်ပါဝင်မှုကို ကြာကြာ ထိန်းပေးပါတယ်။

၂။ အစအဆုံး အလုပ်လုပ်တဲ့ script သေးသေး စရေး

အလွှာတွေ မခွဲခင် စာကြောင်း ၅၀ လောက်နဲ့ input ကနေ output အထိ အလုပ်လုပ်တာ အရင်ရအောင်လုပ်ပါ။

၃။ နာလာမှ အလွှာခွဲ

Validation၊ storage နဲ့ report တွေ ရောနေလို့ ပြင်ရခက်လာတဲ့အခါ class နဲ့ module တွေအဖြစ် ခွဲပါ၊ ဒီ lesson ရဲ့ capstone လိုပါပဲ။

၄။ Logic အပိုင်းကို test ရေး

I/O မပါတဲ့ class တွေကို Minitest နဲ့ စမ်းပါ။ ဒါက အရင် lesson တွေက ပေးထားတဲ့ ကိရိယာပါပဲ။

၅။ တစ်ဦးဦးရဲ့ gem source ကို ဖတ်

gem which နဲ့ file တည်နေရာ ရှာပြီး သေးသေးလေး ဖတ်ကြည့်ပါ။ ကိုယ်ရေးပုံနဲ့ တခြားသူရေးပုံ နှိုင်းယှဉ်တာက အမြန်ဆုံး သင်ယူနည်းတစ်ခုပါ။

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

ဒီ capstone ရဲ့ ပုံစံက ပရော်ဖက်ရှင်နယ် Ruby code မှာ နေရာတိုင်းနီးပါး ပေါ်ပါတယ်။ Rails app တစ်ခုထဲမှာ model တွေက validation နဲ့ domain စည်းမျဉ်းတွေကို ကိုင်ပြီး၊ Enumerable နဲ့ ဆင်တူတဲ့ ActiveRecord relation တွေက map၊ group_by လို method တွေ ပေးပါတယ်၊ Rake task တွေက import လို အလုပ်တွေကို command အဖြစ် run ပါတယ်။ Homebrew နဲ့ Jekyll လို လူသိများတဲ့ tool တွေလည်း Ruby နဲ့ ရေးထားတာမို့ နေ့စဉ်သုံး tool တွေရဲ့ source ကိုပဲ ကိုယ့်သင်ယူမှုရဲ့ စာအုပ်အဖြစ် သုံးလို့ ရပါတယ်။

အလုပ်ထဲမှာ အချိန်အများစုက code အသစ်ရေးတာထက် ရှိပြီးသား code ကို ဖတ်ပြီး ပြင်တာပါ။ ဒါကြောင့် အလွှာတွေ ရှင်းရှင်းခွဲထားတဲ့ code က အဖွဲ့အတွက် အဖိုးတန်ပါတယ်၊ bug တစ်ခု တွေ့ရင် ဘယ်ဖိုင်မှာ ရှာရမလဲ ချက်ချင်း သိလို့ပါ။ ဒီ lesson မှာ လေ့ကျင့်ခဲ့တဲ့ ပယ်ချတဲ့ row တွေကို အကြောင်းရင်းနဲ့ မှတ်တမ်းတင်တာလည်း production မှာ အရေးကြီးပါတယ်၊ တိတ်တိတ်ကလေး ပျောက်သွားတဲ့ data ထက် အကြောင်းရင်းပါတဲ့ error က အမြဲပိုကောင်းပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

၁။ Tutorial ကူးခုန်ခြင်း

Course တစ်ခုပြီးတာနဲ့ နောက်တစ်ခု ချက်ချင်း စတာက တိုးတက်သလို ခံစားရပေမယ့် ကိုယ်တိုင်ရေးတဲ့ code မရှိရင် ဗဟုသုတက မနစ်ပါဘူး။ ခက်လာတဲ့အချိန်မှာ အသစ်ကို မရွေးဘဲ project ကိုပဲ ဆက်လုပ်ပါ။

၂။ Ruby အခြေခံမပြည့်ခင် Rails ကို ခုန်ဝင်တာ

Rails က Ruby ရဲ့ block၊ module၊ metaprogramming ကို အများကြီး သုံးထားလို့ အခြေခံမခိုင်ရင် Rails ရဲ့ "မှော်" က နားမလည်နိုင်တဲ့အရာ ဖြစ်နေပါတယ်။ ဒီ course ရဲ့ အခြေခံတွေကို project တစ်ခုနဲ့ ခိုင်ပြီးမှ ဝင်ပါ။

၃။ Error ကို ကျော်ပြီး ဒေတာ တိတ်တိတ်ပျောက်စေတာ

rescue => e နဲ့ ဘာမှ မမှတ်ဘဲ ကျော်လိုက်ရင် import ပြီးတဲ့အခါ row ဘယ်နှစ်ကြောင်း ပျောက်လဲ ဘယ်သူမှ မသိပါဘူး။ ဒီ capstone လို ValidationError ကိုပဲ ဖမ်းပြီး "row 6: amount is not a number" လို အကြောင်းရင်းကို စာရင်းထဲ ထည့်ပါ။

၄။ ပိုက်ဆံကို Float နဲ့ သိမ်းတာ

0.1 + 0.2 က 0.30000000000000004 ဖြစ်သလို float နဲ့ ပေါင်းတာတွေက တိတိကျကျ မကိုက်နိုင်ပါဘူး။ ပိုက်ဆံကို cent လို integer နဲ့ သိမ်းပြီး ပြတဲ့အခါမှ format("%.2f", cents / 100.0) နဲ့ ပြောင်းပါ။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Topic အသစ်တိုင်းကို project သေးသေးတစ်ခုအဖြစ် ပြောင်းပါ။ ဥပမာ ဒီ lesson ရဲ့ capstone ကို ကိုယ့်ဒေတာနဲ့ လဲပြီး ပြန်ရေးပါ။
  • Class တစ်ခုစီကို လုပ်ငန်းတစ်ခုပဲ ပေးပါ၊ validation အတွက် class၊ သိမ်းဖို့ class၊ ပြဖို့ method။
  • မှားနိုင်တဲ့ input အားလုံးအတွက် ရှင်းလင်းတဲ့ error class တစ်ခုနဲ့ အကြောင်းရင်း message ပေးပါ။
  • Code တစ်ခုပြီးတိုင်း ကိုယ့်ကိုယ်ကို စစ်တဲ့ self-check ဒါမှမဟုတ် Minitest test တစ်ခုခု ထည့်ထားပါ။

Mini challenge

Mini challenge: စာအုပ်စင် importer

Capstone ရဲ့ ပုံစံကိုပဲ ကိုယ့်ကိုယ်ကိုယ် ထပ်ရေးပါ၊ ဒါပေမယ့် domain က စာအုပ်စင်ပါ။ Raw row တွေကို Book object အဖြစ် ပြောင်းပြီး ပယ်ချတာတွေကို အကြောင်းရင်းနဲ့ စာရင်းပြုကာ JSON အဖြစ် သိမ်းပြီး ပြန်ဖတ်ပါ။

  • Book က title၊ pages၊ status (todo၊ reading၊ done) ကို စစ်ပြီး မမှန်ရင် BookError ကို raise လုပ်ရမယ်
  • Statistics module က total_pages နဲ့ count_by_status ပေးပြီး Enumerable ပါတဲ့ Shelf ထဲ include လုပ်ရမယ်
  • Row ကို Integer(pages) နဲ့ ပြောင်းပြီး each_with_index ထဲမှာ ArgumentError နဲ့ BookError ကို row တစ်ခုစီ ဖမ်းကာ "row 4: ..." ပုံစံ စာရင်းပြုရမယ်
  • Dir.mktmpdir ထဲမှာ JSON နဲ့ သိမ်းပြီး ပြန်ဖတ်ကာ ဒေတာ တူလားဆိုတာ ရိုက်ထုတ်ရမယ်
bookshelf.rb
require "json"
require "tmpdir"

# TODO: class BookError < StandardError

# TODO: module Statistics with total_pages and count_by_status (it relies on Enumerable)

# TODO: class Book: keyword arguments title:, pages:, status:; validate all three;
#       also a to_h that returns a hash with those keys

# TODO: class Shelf: include Enumerable and Statistics, define each, add a << method

rows = [
  ["Ruby Basics", "320", "reading"],
  ["Blocks in Depth", "180", "done"],
  ["Testing Notes", "240", "todo"],
  ["Mystery Novel", "many", "todo"],
  ["Someday Book", "200", "someday"]
]

# TODO: import the rows, collecting problems such as: row 4: invalid value for ...
# TODO: print the book count and pages, count per status, and the problems
# TODO: save as JSON in a temp folder, load it back and print whether the data matches

ရလဒ်: ရလဒ် ကိုးကြောင်း ထွက်ရပါမယ်: 3 books, 740 pages done: 1 reading: 1 todo: 1 Problems: row 4: invalid value for Integer(): "many" row 5: unknown status 'someday' Reloaded: 3 books, 740 pages Same data: true

အရိပ်အမြွက် ကြည့်ရန်

each ကို @books.each(&block) နဲ့ ရိုးရိုး ပေးလို့ရပါတယ်၊ block မပါရင် Array က enumerator ပြန်ပေးတာမို့ ပြဿနာမရှိပါဘူး။ ပြန်ဖတ်တဲ့အခါ symbolize_names: true ထည့်ပြီး Book.new(**attributes) လို့ ခေါ်ပါ။

အဖြေ ကြည့်ရန်
bookshelf.rb
require "json"
require "tmpdir"

class BookError < StandardError; end

module Statistics
  def total_pages = sum(&:pages)

  def count_by_status = group_by(&:status).transform_values(&:count)
end

class Book
  STATUSES = %w[todo reading done].freeze

  attr_reader :title, :pages, :status

  def initialize(title:, pages:, status:)
    raise BookError, "title is required" if title.strip.empty?
    raise BookError, "pages must be positive" unless pages.positive?
    raise BookError, "unknown status '#{status}'" unless STATUSES.include?(status)

    @title = title.strip
    @pages = pages
    @status = status
  end

  def to_h = { title: title, pages: pages, status: status }
end

class Shelf
  include Enumerable
  include Statistics

  def initialize(books = [])
    @books = books
  end

  def <<(book)
    @books << book
    self
  end

  def each(&block) = @books.each(&block)
end

rows = [
  ["Ruby Basics", "320", "reading"],
  ["Blocks in Depth", "180", "done"],
  ["Testing Notes", "240", "todo"],
  ["Mystery Novel", "many", "todo"],
  ["Someday Book", "200", "someday"]
]

shelf = Shelf.new
problems = []
rows.each_with_index do |(title, pages, status), index|
  shelf << Book.new(title: title, pages: Integer(pages), status: status)
rescue ArgumentError, BookError => e
  problems << "row #{index + 1}: #{e.message}"
end

puts "#{shelf.count} books, #{shelf.total_pages} pages"
shelf.count_by_status.sort.each { |status, count| puts "  #{status}: #{count}" }
puts "Problems:"
problems.each { |problem| puts "  #{problem}" }

Dir.mktmpdir do |dir|
  path = File.join(dir, "shelf.json")
  File.write(path, JSON.generate(shelf.map(&:to_h)))
  saved = JSON.parse(File.read(path), symbolize_names: true)
  copy = Shelf.new(saved.map { |attributes| Book.new(**attributes) })
  puts "Reloaded: #{copy.count} books, #{copy.total_pages} pages"
  puts "Same data: #{copy.map(&:to_h) == shelf.map(&:to_h)}"
end

Quick Quiz 1 / 3

ကိုယ်ပိုင် class တစ်ခုထဲ include Enumerable လုပ်ရင် အနည်းဆုံး ဘယ် method ကို define လုပ်ထားရမလဲ။

Quick Quiz 2 / 3

Capstone ရဲ့ import loop က row 6 (amount "n/a") ကို ဘာလုပ်လဲ။

Quick Quiz 3 / 3

Capstone က ပိုက်ဆံကို integer cent နဲ့ သိမ်းတာ ဘာကြောင့်လဲ။

မှတ်ထားရမယ့် အချက်များ

  • Project တစ်ခုက အလွှာတွေ (validation၊ storage၊ report) ကို ခွဲပြီး တစ်ခုစီက အလုပ်တစ်ခုပဲ လုပ်ပါတယ်။
  • each ကို define လုပ်ပြီး Enumerable ကို include လုပ်ရင် ကိုယ်ပိုင် collection က map၊ group_by၊ sum စတာ အားလုံး ရပြီး mixin module က domain logic ကို ထပ်ထည့်ပေးပါတယ်။
  • Row တစ်ခုစီမှာ ကိုယ့် error class ကိုပဲ rescue လုပ်ပြီး အကြောင်းရင်းကို မှတ်ထားရင် ဒေတာ တိတ်တိတ်မပျောက်ပါဘူး၊ ပိုက်ဆံကို integer cent နဲ့ သိမ်းပါ။
  • လမ်းကြောင်း (language၊ tooling၊ web၊ automation) တစ်ခုရွေးပြီး project သေးသေးတစ်ခုနဲ့ စပါ။

Ruby 4.0 Release — Ruby

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Next Steps | Thuta Learning