【问题标题】:How to use persist values outside Views and Controllers in Rails6如何在 Rails6 中的视图和控制器之外使用持久值
【发布时间】:2021-06-08 08:33:25
【问题描述】:

我是 Rails 的新手,我想保留一个作为表单输入的值。所以这个值将在控制器和视图之外的适配器类中使用。我已阅读 cookie 和会话不是最好的方法。

# app/controller/somewhere.rb
class MyController > ApplicationController
    def input_capture
       form_value = "xxxxxx"
       ** # i need to do something with this value to access it in the adapter  
# app/adapters/someadapter.rb
class MyAdapter
    def self.some_method
        form_value

【问题讨论】:

  • 为什么不使用 ActiveRecord?

标签: ruby-on-rails


【解决方案1】:

我不确定我是否完全理解了这个问题,但如果我没记错的话,您正在尝试将表单中的值传递到您的适配器中。在这种情况下,您可以在控制器中初始化适配器并传递值,做您需要做的事情,然后返回值。

class MyController < ApplicationController

  private
  def input_capture
    @value = MyAdapter.new(form_value).execute
  end
end

class MyAdapter
  def initialize(value)
    @value = value
  end

  def execute
    #do what you need to do with the @value
    @value
  end
end

顺便说一句,您的控制器没有正确继承 ApplicationController。如果这是你想要做的,你应该这样做

class MyController < ApplicationController

而不是

class MyController > ApplicationController

另外,如果您尝试实现适配器设计模式,我建议您通读一些有关设计模式实现的文档和示例。这里有一些希望有用的链接

https://refactoring.guru/design-patterns/adapter/ruby/example

https://www.sitepoint.com/using-and-testing-the-adapter-design-pattern/

【讨论】:

  • 谢谢!大开眼界
猜你喜欢
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-18
  • 2013-07-19
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
相关资源
最近更新 更多