Rails 7如何装饰非ActiveRecord对象



在我的Rails 7应用程序中,我有一个想要装饰的数据表。数据来自API响应,因此实际上它是一个散列数组。如下所示:

# transactions_controller.rb
class TransactionsController < ApplicationController
def index
response = client.transactions.list(platform_id: current_user.platform_id, page: 1, per_page: 100)
@transactions = response.body['data']
end
private
def client
@client ||= TestAPI::Client.new
end
end

现在,在transactions/index.html.erb中,我有一个包含@transactions数据的表,我想装饰它:

#views/transactions/index.html.erb
<table class="table table-striped">
<thead>
<tr>
<b>
<tr>
<th>Date</th>
<th>Amount</th>
</tr>
</b>
</tr>
</thead>
<tbody>
<% @transactions.map do |transaction| %>
<tr>
<td>
<%= transaction['created_at'] %>
</td>
<td>
<%= transaction['amount_cents'] %>
</td>
</tr>
<% end %>
</tbody>
</table>

我知道我可以在视图文件中注入这样的逻辑:

(...)
<td>
<%= Date.parse(transaction['created_at']).strftime("%d.%m.%Y") %>
</td>
<td>
<%= "#{ transactions_data.last['amount_cents']/100}" "#{ transactions_data.last['currency']}" %>
</td>
(...)

但我想从这个角度摆脱这种逻辑,因为我将来在这里会有越来越多的逻辑。

想要从视图中删除逻辑值得称赞。

您需要一个新对象,它可以被称为TransactionPresenter或您选择的任何对象。它将实现视图逻辑。所以在你的TransactionsController:

def index
response = client.
transactions.
list(platform_id: current_user.platform_id, page: 1, per_page: 100).
map{|t| TransactionPresenter.new(t)}
@transactions = response.body['data']
end

TransactionPresenter模型可能是这样的:

class TransactionPresenter
def initialize(transaction)
# capture the fields of interest as variables
end
def amount
"$#{amount_cents.to_f/100}" # for example, whatever makes sense in your context
end
end

因此所有逻辑都从视图中删除:

<table>
<% @transactions.each do |transaction| %>
<tr><%= transaction.amount %></tr>
<% end %>
</table>

最新更新