iT邦幫忙

2021 iThome 鐵人賽

DAY 14
0
Software Development

在 Ruby on Rails 中導入 Domain-Driven Design 是不是搞錯了什麼?系列 第 14

[Day14] Boxenn 實作 Source Wrapper

Source Wrapper

source wrapper 的職責很簡單,他負責將外部資源的介面轉換給 Boxenn::Repository 使用。
Boxenn::Repository 總共用了三個 method :

  • find_by(hash)
    透過 primary key 找尋資料,input 為 entity 上設定的 primary key 的 hash。須回傳物件,回傳的物件會再傳給 Boxenn::Repositories::Factory 建成 entity。
  • save(hash, hash)
    新建或更新資料庫的資料,input 為 entity 上設定的 primary key 的 hash 及對應 schema column 的 hash
  • destroy(hash)
    刪除資料庫裡的資料,input 為 entity 上設定的 primary key 的 hash

範例

範例的外部資源是使用 ActiveRecord 的 Model。

class Order < Boxenn::Repositories::SourceWrapper
  param :source, default: -> { Models::Order } # 這邊的 order 是 active record 的 model

	def find_by(primary_keys)
		source.find_by(primary_keys)
	end

  def save(primary_keys, attributes)
    record = source.find_or_initialize_by(primary_keys)
    record.assign_attributes(attributes)
    record.save!
  end

	def destroy(primary_keys)
    record = source.find_by(primary_keys)
    record.destroy!
	end
end

下一篇我們就可以簡單地使用 Boxenn::Repository 來操作資料庫,另外會介紹 Boxenn::Repositories::Query,用來收斂複雜的 sql query。


上一篇
[Day13] 擴充 Boxenn 的 Record Mapper
下一篇
[Day15] Boxenn 實作 Repository & Query
系列文
在 Ruby on Rails 中導入 Domain-Driven Design 是不是搞錯了什麼?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言