Attach a method to a module

70 views Asked by At

I have this piece of code:

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

And I have a method:

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

How should I attach it to the first code, so I can use (@adapter = Encryption::Adapters.const_get("#{adapter_name**.pascalize_string**}").

I keep getting this error:

C:/Users/Ian/Desktop/Alpha/encryption/adapters/adapter.rb:23:in `adapter=': undefined method `pascalize_string' for :caesar:Symbol (NoMethodError)

1

There are 1 answers

3
Simone Carletti On

Just define it inside the method.

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

It should be called with

pascalize_string(string)

not

string.pascalize_string

because you are defining it into the module, not in the String module.

There are a few other strange things in your code, such as the use of :@adapter, but they are not relevant to the topic of this question hence I left them as they are.