将方法附加到模块

时间:2015-06-17 17:10:43

标签: ruby methods module adapter

我有这段代码:

    private void ribbonDialogLauncherImpl1_Click(object sender, RibbonControlEventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();
    }

    private void group1_DialogLauncherClick(object sender, RibbonControlEventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();
    }

我有一个方法:

module Encryption
  extend self

  def adapter
    return @adapter if @adapter
    self.adapter = :@adapter
    @adapter
  end


  def adapter=(adapter_name)
    case adapter_name
    when :@adapter
    require_relative  "#{adapter_name}"
   # @adapter = Encryption::Adapters.const_get("#{adapter_name.pascalize_string}")

    @adapter = Encryption::Adapters.const_get("#{adapter_name.pascalize_string}")
  else
    raise "Missing adapter #{adapter_name.pascalize_string}"
    end
    end

  def new(key)
    print key
    adapter.new(key)
  end

end

我应该如何将它附加到第一个代码,因此我可以使用def pascalize_string(string) return string if string !~ /_/ && string =~ /[A-Z]+.*/ string.split('_').map { |part| part.capitalize }.join end

我一直收到这个错误:

  

C:/Users/Ian/Desktop/Alpha/encryption/adapters/adapter.rb:23:在       `adapter =&#39 ;: undefined method`pascalize_string' for:caesar:符号       (NoMethodError)

1 个答案:

答案 0 :(得分:2)

只需在方法中定义它。

module Encryption
  extend self

  def adapter
    return @adapter if @adapter
    self.adapter = :@adapter
    @adapter
  end

  def pascalize_string(string)
    return string if string !~ /_/ && string =~ /[A-Z]+.*/
    string.split('_').map { |part| part.capitalize }.join
  end

  def adapter=(adapter_name)
    case adapter_name
    when :@adapter
      require_relative adapter_name
      @adapter = Encryption::Adapters.const_get(pascalize_string(adapter_name))
    else
      raise "Missing adapter #{pascalize_string(adapter_name)}"
    end
  end

  def new(key)
    print key
    adapter.new(key)
  end

end

应该用

调用
pascalize_string(string)

string.pascalize_string

因为您将其定义到模块中,而不是String模块中。

您的代码中还有一些其他奇怪的内容,例如使用:@adapter,但它们与此问题的主题无关,因此我将它们保留原样。