我有类HomeController
class HomeController < ApplicationController
def event_one
Req = **endpoint.connection**
res = req.body**(json format)**
@events = res
end
def event_two
@events
end
end
我可以使用一个实例变量(@events)从event_one方法获取来自端点的响应,来自另一个event_two方法。
答案 0 :(得分:2)
尝试使用此DRY代码:
class HomeController < ApplicationController
before_action :set_events, only: [:event_one, :event_two]
def event_one
#your code here
# for example puts @events
end
def event_two
#your code here
# for example puts @events
end
private
def set_events
req = **endpoint.connection**
res = req.body**(json format)**
@events = res
end
end
答案 1 :(得分:1)
您可以使用私有方法来设置evnets
class HomeController < ApplicationController
def event_one
set_events
end
def event_two
set_events
end
private
def set_events
Req = **endpoint.connection**
res = req.body**(json format)**
@events = res
end
end
您也可以使用要为此控制器的每个操作设置的过滤器来调用此方法。
希望这会有所帮助!