ruby-on-rails - rails : Make Route Helper Methods Available to PORO

标签 ruby-on-rails ruby

在我的 Rails 应用程序中的普通旧 Ruby 对象 (PORO) 中:我有以下方法:

def some_method
  content_tag(:li, link_to("Do something", somewhere_path(object.id)))
end

首先:对象不理解方法 content_tag,所以我添加了以下内容,使对象理解该方法:

include ActionView::Helpers::TagHelper

然后对象不理解 link_to 所以我添加了以下内容使对象理解该方法:

include ActionView::Helpers::UrlHelper

现在,它不理解我的路线:somewhere_path(object.id)

问题:如何让我的 Rails 应用程序中的 PORO 理解生成路线的助手?

后续问题:是否有更简单的方法将所有这些功能包含到我的 PORO 对象中?也许有一种方法可以只包含一个主要模块并获得所有这些功能(而不是可能需要 3 个不同的模块)。

最佳答案

您要么必须执行您在 self 回答(链接到 revision I refer to )中描述的操作,要么将一些上下文注入(inject)您的 PORO。上下文是知道所有这些方法的地方。像这样:

class ProjectsController
  def update
    project = Project.find(params[:id])
    presenter = Presenters::Project.new(project, context: view_context) # your PORO
    # do something with presenter
  end
end

你的 PORO 看起来像这样:

module Presenters
  class Project
    attr_reader :presentable, :context
    def initialize(presentable, context:)
      @presentable = presentable
      @context = context
    end

    def special_link
      context.somewhere_path(presentable)
    end
  end
end

我,我两个都不喜欢。但有时我们不得不选择一个较小的邪恶。

If anyone happens to know of a current way to get access to all of these methods with one include statement then let me know.

为什么,是的。有办法。

module MyViewCompatibilityPack
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::UrlHelper

  def url_helpers
    Rails.application.routes.url_helpers
  end
end

class MyPoro
  include MyViewCompatibilityPack

  ...
end

关于ruby-on-rails - rails : Make Route Helper Methods Available to PORO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355582/

相关文章:

arrays - ruby 散列作为数组的第一个元素

Ruby Regex,获取所有可能的匹配项(不截断字符串)

ruby-on-rails - 如何让 Annotate gem 工作?

ruby-on-rails - ActiveAdmin、Formtastic 和 Paperclip : Not Rendering File Dialog

ruby-on-rails - tinymce 图片上传后服务器响应错误

ruby - 它是 JSON 数组吗?

ruby-on-rails - 如何在 Ruby Views 中制作漂亮的 UI

ruby-on-rails - 在 ruby​​ 中使用 .split 拆分 unicode(我认为)

ruby-on-rails - 在 Redis 中使用特定模式获取键范围的最佳方法

jquery - Rails Jquery 复选框