2015-01-26 76 views
1

我創建了以下模塊:如何動態定義實例哈希?

module SlackHelper 
    def alert_slack(message) 
    notifier.ping.message 
    end 

    private 

    def notifier(channel="default") 
    @notifier[channel]||= Slack::Notifier.new ENV['SLACK_WEBHOOK_URL_' + channel] 
    end 
end 

以前這是沒有渠道編寫的,它的工作。我得到的錯誤是:

undefined method `[]' for nil:NilClass 

回答

1
@notifier ||= Hash.new{|hsh, k| hsh[k] = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL_' + k]} 

有了這個您的哈希被配置爲自動建立Slack::Notifier當你訪問一個新的密鑰。

所以你只需要做:@notifier[channel]它得到instanciated。

所以,你可以擺脫你的私人notifier方法做:

def alert_slack(message,channel='default') 
    @notifier ||= Hash.new{|hsh, k| hsh[k] = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL_' + k]} 
    @notifier[channel].ping message 
end 
+0

最大的問題是在哪裏把這個定義在這種情況下。由於OP定義了模塊實例方法,這意味着該模塊將被包含在某個類中 - 您需要在該類實例上設置該實例變量,這不是那麼容易的任務。 – BroiSatse 2015-01-26 23:49:07

+0

然後使用通知器方法,並在裏面做,但只是一種方法,這是沒用的 – Geoffroy 2015-01-26 23:51:49

+1

我做了這些更改: 'def alert_slack(message,channel ='default')' '@notifier [channel] .ping message ' 這個方法和@BrioSatse提交的方法都有效,我沒有資格知道哪個更好。 PS我該如何添加換行符以評論? – William 2015-01-27 00:03:08

1

嘗試:

def notifier(channel="default") 
    @notifier ||= {} 
    @notifier[channel] ||= Slack::Notifier.new ENV['SLACK_WEBHOOK_URL_' + channel] 
end 
+0

我最終使用這種方法,因爲我覺得它更容易閱讀。 – William 2015-01-27 01:34:10