缺少红宝石的方法

问题描述 投票:0回答:1

我需要一些帮助的人。我有一个作业-为ruby创建简单的DSL配置。而所有的问题是method_missing我需要打印出键的值,但是它们是自动打印出来的,而不是通过命令打印出来的。

init.rb:

require_relative "/home/marie/dsl/store_application.rb"

config = Configus.config do |app|
  app.environment = :production

  app.key1 = "value1"
  app.key2 = "value2"

  app.group1 do |group1|
    group1.key3 = "value3"
    group1.key4 = "value4"
  end
end

store_application.rb:

class Configus
  class << self
    def config
      yield(self)
    end

    #    attr_accessor :environment,
    #                  :key1,
    #                  :key2,
    #                  :key3,
    #                  :key4

    def method_missing(m, args)
      puts args
    end

    def group1(&block)
      @group1 ||= Group1.new(&block)
    end
  end

  class Group1
    class << self
      def new
        unless @instance
          yield(self)
        end
        @instance ||= self
      end

      # attr_accessor :key1,
      #               :key2,
      #               :key3,
      #               :key4

      def method_missing(m, *args)
        p m, args
      end
    end
  end
end

ruby init.rb输出:

marie@marie:~/dsl$ ruby init.rb 
production
value1
value2
:key3=
["value3"]
:key4=
["value4"]

问题是值会自动打印,我需要通过以下方式将它们打印出来:

config.key1         => 'value1'
config.key2         => 'value2'
config::Group1.key3 => 'value3'
config::Group1.key4 => 'value4'

感谢您的帮助..

ruby dsl method-missing
1个回答
0
投票

尝试像这样使用字符串插值来定义缺少的方法:

def method_missing(m, args)
  puts "config:#{m}        #{args}"
end

有关其工作原理的更多信息,请参见https://docs.ruby-lang.org/en/2.6.0/syntax/literals_rdoc.html

© www.soinside.com 2019 - 2024. All rights reserved.