sensu-plugins / sensu-plugins-mailer

This plugin is an email handler for Sensu.
http://sensu-plugins.io
MIT License
17 stars 37 forks source link

Code explanation #60

Open oquidave opened 6 years ago

oquidave commented 6 years ago

Am sorry, but I have failed to wrap my mind around this piece of code. Am a ruby newbie.

option :json_config,
         description: 'Config Name',
         short: '-j JsonConfig',
         long: '--json_config JsonConfig',
         required: false,
         default: 'mailer-mailgun'

  def json_config
    @json_config ||= config[:json_config]
  end

I don't understand the first part. Is this a dictionary or a hash? and then what does this @json_config ||= config[:json_config] do? I know it has something to do with getting the mailgun json configurations from the .json file. But where is the config hash coming from?

I am using this handler to send emails for events, but am also trying to learn the code so as to write my own custom handler based on this example. Thanks.

majormoses commented 6 years ago

No need for apology, wanting to learn is a great thing. I will attempt my best to explain it and provide additional reading/explanations.

I don't understand the first part. Is this a dictionary or a hash?

According to this which I validated here, option is coming from sensu-plugin gem that we use for a base class for ruby based community plugins. This is really just getting the actual options from mix-cli you can check out their readme for a quick idea of whats going on. If you want to go deeper you can read through the code here. The short answer is that each options is a hash of hashes.

what does this @json_config ||= config[:json_config] do?

When you see a variable like this @somevarname it is an instance variable. The following ||= are a combination of operators; || which is an OR statement and = for assignement. It's also taking a shortcut and is more understandable as @json_config = @json_config || config[:json_config]. Putting it all together it is saying that it will always return the instance variable @json_config as either itself or what config[json_config] is. I think this probably does a better job explaining it than I did.

Let me know if there is anything else I can help with.

asachs01 commented 5 years ago

@oquidave hi :wave: ! Since this isn't so much an issue with the plugin, are you comfortable closing it?