日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

诗歌rails 之自定义Helper模块

發布時間:2023/12/10 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 诗歌rails 之自定义Helper模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
關鍵字: Rails Helper Rails默認為每個controller指定一個helper,所有的helper都放在app/helpers目錄下
但是有些Helper我們希望是全局共享的,一般我們將這些Helper方法都扔在ApplicationHelper模塊里
其實我們可以在app/helpers目錄下建立我們自定義的Helper模塊,如formatting_helper、path_helper等
ruby代碼
  • #?formatting_helper.rb??
  • module?FormattingHelper??
  • ??def?free_when_zero(price)??
  • ????price.zero????"FREE"?:?number_to_currency(price)??
  • ??end??
  • ??
  • ??def?yes_no(bool)??
  • ????bool??'Yes'?:?'No'??
  • ??end??
  • end??
  • ??
  • #?path_helper.rb??
  • module?PathHelper??
  • ??def?articles_path_for_article(article)??
  • ????if?article.tip???
  • ??????tips_articles_path??
  • ????else??
  • ??????news_articles_path??
  • ????end??
  • ??end??
  • ??
  • ??def?product_path(product)??
  • ????if?product.kind_of??Book??
  • ??????book_path(product)??
  • ????else??
  • ??????movie_path(product)??
  • ????end??
  • ??end??
  • end??
  • # formatting_helper.rb module FormattingHelper def free_when_zero(price) price.zero? ? "FREE" : number_to_currency(price) end def yes_no(bool) bool? 'Yes' : 'No' end end # path_helper.rb module PathHelper def articles_path_for_article(article) if article.tip? tips_articles_path else news_articles_path end end def product_path(product) if product.kind_of? Book book_path(product) else movie_path(product) end end end 要想使用這些Helper,我們只需修改ApplicationController即可
    ruby代碼
  • class?ApplicationController?<?ActionController::Base??
  • ??helper?:formatting,?:path??
  • end??
  • class ApplicationController < ActionController::Base helper :formatting, :path end 或者直接使用helper :all來使用所有的Helper

    轉載于:https://www.cnblogs.com/orez88/articles/1520407.html

    創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

    總結

    以上是生活随笔為你收集整理的诗歌rails 之自定义Helper模块的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。