2015-01-26 44 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