為 api 和前端開發 rails 應用程式。所以我們有用于 api 的產品控制器和用于前端的產品控制器,而 Product 模型是兩者之一。
像那樣
class Api::V1::ProductsController < ActionController::API
def create
@product.save
end
end
class ProductsController < ActionController::Base
def create
@product.save
render @product
end
end
class Product < ActiveRecord::Base
def weight=(value)
weight = convert_to_lb
super(weight)
end
end
基本上在產品中,我們有“重量欄位”,這個欄位基本上是從倉庫中獲取重量。對于用戶來說,這將是不同的單位。所以我將保存按單位捕獲的任何重量,它的磅、克或石頭,但它會轉換為磅并存盤到資料庫中。
所以我寫了對話的覆寫方法。但我希望這個覆寫方法應該只呼叫前端應用程式而不是 api。因為 api 總是以磅為單位發布重量(它需要在客戶端轉換)
你們有人能提出解決方案嗎?對于這種情況,我應該使用什么或我應該做什么。建議是否還有針對這種情況的任何其他解決方案。
uj5u.com熱心網友回復:
最好保持Product模型盡可能簡單(單一職責原則)并將權重轉換保持在外面。
我認為使用裝飾器模式會很棒。想象一下這樣作業的類:
@product = ProductInKilogram.new(Product.find(params[:id]))
@product.update product_params
@product.weight # => kg weight here
所以,你應該使用這個新ProductInKilogram的Api::V1::ProductsController而已。
你可以選擇實作它。
遺產
class ProductInKilogram < Product
def weight=(value)
weight = convert_to_lb
super(weight)
end
end
product = ProductInKilogram.find(1)
product.weight = 1
這很容易,但 ProductInKilogram 的復雜性很高。例如,您不能在沒有資料庫的情況下單獨測驗此類。
簡單委托
class ProductInKilogram < SimpleDelegator
def weight=(value)
__getobj__.weight = convert_to_lb(value)
end
end
ProductInKilogram.new(Product.find(1))
純紅寶石(我的最愛)
class ProductInKilogram
def initialize(obj)
@obj = obj
end
def weight=(value)
@obj.weight = convert_to_lb(value)
end
def weight
convert_to_kg @obj.weight
end
def save
@obj.save
end
# All other required methods
end
看起來有點冗長,但它很簡單。測驗這樣的類很容易,因為它對持久性沒有任何作用。
鏈接
- 單一職責原則
- 委托寶石
- Ruby 中的裝飾器模式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358367.html
