簡體   English   中英

Ruby-如何訪問模塊的方法?

[英]Ruby - How to access module's methods?

我正在使用Forem gem安裝論壇。 有一個選項允許頭像個性化,因為可以使用Facebook登錄。 您只需在用戶模型中指定方法即可。

# Forem initializer
Forem.avatar_user_method = 'forem_avatar'

# User model
def forem_avatar
  unless self.user_pic.empty?
    self.user_pic
  end
end

但是我想讓Gravatar退回普通的非Facebook帳戶。 我已經在Forem上找到了該方法,並且從理論上講,我需要調用avatar_url方法:

# User model
def forem_avatar
  unless self.user_pic.empty?
    self.user_pic
  else
    Forem::PostsHelper.avatar_url self.email
  end
end

但是,Forem不是實例,而是模塊,我無法調用它也不能創建新實例。 簡單的方法是復制該方法的行,但這不是重點。 有辦法嗎?

謝謝

更新資料

這兩個答案都是正確的,但是當我以任何一種方式調用方法時,都會出現此undefined local variable or method 'request'錯誤,這是原始avatar_url的最后一行。

有沒有辦法像在PHP中那樣全球化該對象? 我是否必須手動傳遞該參數?

也許像這樣重新打開模塊:

module Forem
  module PostsHelper
    module_function :avatar_url
  end
end

然后調用Forem::PostsHelper.avatar_url

如果avatar_url調用其他模塊方法,則也必須通過module_function “打開”它們

或僅在您的類中include Forem::PostsHelper並直接使用avatar_url ,而無需Forem::PostsHelper命名空間

如果您希望能夠在用戶類中使用這些方法,請包括它們並使用

class User < ActiveRecord::Base
  include Forem::PostsHelper

  def forem_avatar
    return user_pic if user_pic.present?
    avatar_url email
  end
end

另一種方法是動態設置Forem.avatar_user_method因為Forem代碼會在使用前檢查它是否存在,如果沒有,默認為avatar_url

class User < ActiveRecord::Base

  # This is run after both User.find and User.new
  after_initialize :set_avatar_user_method

  # Only set avatar_user_method when pic is present
  def set_avatar_user_method
    unless self.user_pic.empty?
      Forem.avatar_user_method = 'forem_avatar'
    end
  end

  def forem_avatar
    self.user_pic
  end
end

這樣,您就不會使用來自Forem的不必要方法來污染模型,也不會偽造Forem本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM