Plastikfan
Plastikfan

Reputation: 4022

What is this Ruby language construct, next to method definition

Just learning Ruby at the moment and I'm also learning how Thor works so I can write a command line application. However, after looking at the examples, I can't figure out what Ruby language construct is appearing before a method definition. Looking at the following code sample ...:

class MyCLI < Thor
  desc "hello NAME", "say hello to NAME"
  options :from => :required, :yell => :boolean
  def hello(name)
    output = []
    output << "from: #{options[:from]}" if options[:from]
    output << "Hello #{name}"
    output = output.join("\n")
    puts options[:yell] ? output.upcase : output
  end
end

... please could you tell me what 'desc' and 'options' are. I know that they provide meta data for the following method, but I don't understand the Ruby syntax. 'desc' is not an instance variable, or obviously not a method, so what is it. Once I know what it is, I can read about it. This is similar to what an attribute is in C#, where a method can be decorated with attributes which can then be inspected by reflection calls. Is this the case with 'desc' if so, what is the syntax and how are they tied to a method (in this case the method hello).

Thanks.

NB: This question is not about Thor; it's just using Thor as an example. The core of the question is the Ruby syntax itself.

Upvotes: 1

Views: 116

Answers (2)

Nafaa Boutefer
Nafaa Boutefer

Reputation: 2359

They are simply class method calls, here desc and here is options defined on the Thor class.

Upvotes: 4

Sasha
Sasha

Reputation: 485

The methods you mention (e.g. desc) form part of Thor's DSL and act as convenience methods for . The method name desc in particular was taken wholesale from Rake.

I'd encourage you to read the source files for Thor to understand how the DSL has been implemented.

Upvotes: 4

Related Questions