在给一家布料店维护一个小的库存同步脚本。它读取事件,按 SKU 累计总数。店里只关心自己所在的区域 us-east,这个值来自 config/shop.yml。所以在 restock 分支里我把 region 写进了哈希模式,以为这样只会匹配我们自己的事件。
def handle(event)
region = @region
@log.debug("handling #{event[:type]} for #{region}")
case event
in { type: "restock", region: region, sku:, qty: }
@totals[sku] += qty
@log.info("restock #{sku} +#{qty} (#{region})")
in { type: "sale", sku:, qty: }
...
而 @region 是在 main.rb 里用 config["region"].strip 构造的。
但日志里有 restock bolt-cotton-12 +40 (eu-west),而且这个 SKU 的总数偏高。那 40 被算进去了。日志那行打印的是事件里的 region,我当时就觉得有点怪,但一开始没太在意。
我最初猜是 YAML 里的字符串和事件里的字符串不一样。冻结、编码、末尾换行之类的。我用 inspect 把两边都打印了出来,us-east 的看起来完全一样。加了 .strip,没变化。跑的是 rbenv 下的 3.1.4,不是会在 in 上报错的旧系统 ruby。
所以这是 YAML 的问题,还是哈希模式本身就是这么工作的?我完全看不出 eu-west 是怎么进来的...
从英语翻译·查看原文Maintaining a little stock-sync script for a fabric shop. It reads events and keeps running totals per SKU. The shop only cares about its own region, us-east, which comes from config/shop.yml. So in the restock branch I put the region in the hash pattern, figuring it would only match our events:
def handle(event)
region = @region
@log.debug("handling #{event[:type]} for #{region}")
case event
in { type: "restock", region: region, sku:, qty: }
@totals[sku] += qty
@log.info("restock #{sku} +#{qty} (#{region})")
in { type: "sale", sku:, qty: }
...
And @region is built in main.rb with config["region"].strip.
But the log has restock bolt-cotton-12 +40 (eu-west) and the total for that SKU is too high. The 40 got counted. The log line printing the region from the event seemed odd to me, but I didn't think much of it at first.
My first guess was the YAML string being different from the event string. Frozen, encoding, a trailing newline, something like that. I printed both with inspect and the us-east ones look identical. Added .strip, no change. It's running under rbenv on 3.1.4, not the old system ruby, which chokes on in.
So is this a YAML thing or is it how hash patterns work? I don't see how eu-west gets in at all...