Search code examples
ruby-on-railsapimoduleplivo

Using a module's methods inside a class


I'm trying to integrate an API into a class but can't work out how I put the modules in place.

class PlivoNumber < ActiveRecord::Base
  require 'plivo'
  include Plivo 

def initialize_plivo

 @p = RestAPI.new(ENV['PLIVO_AUTH_ID'], ENV['PLIVO_AUTH_TOKEN'])
end

def delete_number
  self.initialize_plivo
  params = {
    'number' => self.number
  }
  response = @p.unrent_number(params)

end

I've tried both include and Extend

if I use in initialize

self.RestAPI.new(ENV['PLIVO_AUTH_ID'], ENV['PLIVO_AUTH_TOKEN'])

NoMethodError: undefined method `RestAPI' for #<PlivoNumber:0x007f8eca9523f0>

if I use

RestAPI.new(ENV['PLIVO_AUTH_ID'], ENV['PLIVO_AUTH_TOKEN'])

NameError: uninitialized constant PlivoNumber::RestAPI

Basically I want to be able to run @plivo_number.delete_number and have the app hit the api and perform the action. I appreciate that the initialize step not really doing anything with the class, but I can't do the next step without it.

Hope that makes some kind of sense, I get the impression that what I'm doing is probably a bit confused....


Solution

  • You should be able to access RestAPI class after including Plivo module. Make sure you have installed plivo gem correctly. Here is more rubyish version of your code:

    class PlivoNumber < ActiveRecord::Base
      include Plivo 
    
      def delete_number
        api.unrent_number('number' => number)
      end
    
      private
    
      def api
        @api ||= RestAPI.new(ENV['PLIVO_AUTH_ID'], ENV['PLIVO_AUTH_TOKEN'])
      end
    end
    

    Also you don't need to include Plivo module into PlivoNumber class, you could just use Plivo::RestAPI instead.