简体   繁体   中英

How can I dynamically define an instance hash?

I created the following module:

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

Previously this was written without channels, and it worked. The error that I get is:

undefined method `[]' for nil:NilClass
@notifier ||= Hash.new{|hsh, k| hsh[k] = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL_' + k]}

With this your hash is configured to automatically build the Slack::Notifier when you access a new key.

So you only have to do: @notifier[channel] and it gets instanciated.

So you can get rid of your private notifier method and do:

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

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM