lcoderre
lcoderre

Reputation: 1303

Using mixins during code parsing in Ruby

I want my Configurable module to include a config command to whatever app includes it.

edit: see the update on my reasoning a little further down

I get that error:

cli.rb:2:in '<module:Configurable>': undefined method 'desc' for Configurable:Module (NoMethodError)

I want to do the following in a commandline:

$ app something
> I did something!
$ app config
> You configured the app!
> I did something!

So here's the code:

# app.rb 

require 'thor'
require_relative './cli'

class App < Thor
    include Configurable

    # def initialize ...

    desc "something", "The Cli app does something"
    def something
        puts "I did something!"
    end
end

# cli.rb 
module Configurable
    desc 'config', "You can configure the app"
    def config
        puts "You configured the app!"
        # You can even call App 'something' method
        something 
    end
end

As the above points out, when I comment out the desc 'config' .. line, it builds and runs, although Thor doesn't add the config command.

Thanks for your help!

UPDATE

I downloaded Thor's repo, and added traces when it encountered a desc command. So I tried calling Thor.desc instead, and I could see that it was loaded in Thor's system, but still didn't appear in commands list. So I played around and ended up with the following:

module Configurable
  Thor.desc 'config', 'You can configure the app'
  def config
    puts "You configured the app!"
    # You can even call App 'something' method
    something 
  end

  def self.included(klass)
    puts "The module was included"
    klass.desc "another", "another one"
  end

  def another
    puts "Another!"
  end
end

This way, I tested if calling desc before or after made a difference, but it didn't.

At this point, I would say it's Thor's limitations, and I can't achieve what I want with Thor and mixins.

Upvotes: 1

Views: 89

Answers (1)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

desc is a method of Thor's singleton class, but Configurable isn't an instance of Thor's singleton class. (Obviously.) That's why you can't call desc without a receiver, you will have to call it explicitly:

(Note: I don't have Thor, therefore, I cannot test this. It may or may not work.)

module Configurable
  Thor.desc 'config', 'You can configure the app'
  def config
    puts "You configured the app!"
    # You can even call App 'something' method
    something 
  end
end

Upvotes: 1

Related Questions