【问题标题】:is it possible/good to have two helper class for one controller and view in rails?一个控制器有两个帮助类并在rails中查看是否可能/很好?
【发布时间】:2017-07-06 04:43:54
【问题描述】:

我的视图中有太多需要使用的函数,而我的助手类看起来太长了。那么为单个控制器和视图提供两个帮助程序类是否可能/很好?

如果是,如何定义第二个辅助类?

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    创建一个新的助手:

    1. 为帮助文件选择一个名称,例如 my_helper.rb
    2. 在 /app/helpers 目录中创建文件
    3. 根据文件名创建一个模块。在这种情况下

      module MyHelper
      end
      
    4. 将你的助手定义为方法

      module MyHelper
        def hello_world(name)
          "hello #{name}"
        end
      end
      

    【讨论】:

    • 不需要第 5 步
    【解决方案2】:

    试试这个。

    rails new example_app
    cd example_app/
    rails g scaffold Page title:string
    rake db:migrate
    rails s -p 3001
    

    现在创建 2 个助手:

    touch ./app/helpers/a_helper.rb
    touch ./app/helpers/b_helper.rb
    

    现在将以下模块放入各自的文件中。

    module AHelper
      def same_method_name
        "Hi from AHelper"
      end
    end
    
    module BHelper
      def same_method_name
        "Hi from BHelper"
      end
    end
    

    现在在 ./app/views/pages/index.html.erb 里面把这个辅助方法放在某个地方。

    <%= same_method_name %>
    

    并访问localhost:3001/pages

    您将在页面中看到Hi from BHelper

    所有帮助模块都包含在您的视图中,并将根据它们被包含的顺序相互覆盖。

    现在试试这个:

    module BHelper
      def same_method_name
        "Hi from BHelper #{super}"
      end
    end
    

    super 将继续沿继承链上升,到达名为same_method_name 的下一个方法,该方法是AHelper#same_method_name,因此您将获得"Hi from BHelper Hi from AHelper"

    如果需要快速简单的解决方案,Rails 助手是很好的选择,但如果需要更多封装,请考虑使用装饰器模式(例如使用 Draper 之类的 gem)。

    【讨论】:

      猜你喜欢
      • 2012-01-24
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2018-08-08
      相关资源
      最近更新 更多