我不确定这样做的最佳方法是什么,或者我的想法是否存在根本缺陷。
我有一个控制器,它在其操作上创建一个普通的旧 Ruby 对象 (PORO) 演示者#index
:
# app/controllers/my_controller.rb
class MyController < ApplicationController
def index
@my_presenter = MyPresenter.new(
filter_1: params[:filter_1],
filter_2: params[:filter_2])
end
end
以及使用来自多个模型的数据的演示者:
# app/presenters/my_presenter.rb
class MyPresenter
def initialize(filter_1: nil, filter_2: nil)
@my_data = MyModel.my_scope(filter_1) # scoping in the my_model.rb file
@my_other_data = MyOtherModel.my_scope(filter_1, filter_2)
end
def show(view)
# Somehow call the my_function.js from here and return the result to the view
end
end
最后,提交给演示者的视图:
<!-- app/views/my_controller/index.html.erb -->
<h1>The view</h1>
<%= @my_presenter.show(this) %>
我希望#show
演示者的动作调用一些 JavaScript(用于可视化的 D3 代码),并将结果返回给视图:
// app/assests/javascripts.js
function my_function(data) {
// D3 visualisation to go here...
return null
}
实现这一目标的最佳方法是什么?