class Moodle::Client

Attributes

domain[R]
format[R]
password[R]
protocol[R]
service[R]
token[R]
username[R]

Public Class Methods

new(options={}) click to toggle source
# File lib/moodle/client.rb, line 18
def initialize(options={})
  @username = options[:username] || Moodle.config[:username]
  @password = options[:password] || Moodle.config[:password]
  @domain   = options[:domain]   || Moodle.config[:domain]
  @protocol = options[:protocol] || Moodle.config[:protocol]
  @service  = options[:service]  || Moodle.config[:service]
  @format   = options[:format]   || Moodle.config[:format]
  @token    = options[:token]    || Moodle.config[:token]

  # If no token is provided generate one
  if @token.nil?
    @token = self.obtain_token
  end
end

Public Instance Methods

client() click to toggle source

Retuns a Moodle::Protocol client instance

# File lib/moodle/client.rb, line 34
def client
  if @client.nil?
    # Instantiate the client protocol
    case @protocol
    when 'rest'
      @client = Moodle::Protocol::Rest.new
    else
      @client = Moodle::Protocol::Rest.new
    end
  end
  @client
end
obtain_token() click to toggle source

Obtains a token from the username and password

# File lib/moodle/client.rb, line 48
def obtain_token
  response = client.request(@domain + '/login/token.php', {
    :username => @username, 
    :password => @password, 
    :service  => @service
  })

  parsed = JSON.parse(response)
  parsed['token']
end
request(params={}) click to toggle source

Make a request using the desired protocol and format

# File lib/moodle/client.rb, line 60
def request(params={})
  params.merge!(
    :wstoken => @token,
    :moodlewsrestformat => @format,
    :wsfunction => caller[0][/`.*'/][1..-2]
  )
  response = client.request(@domain + '/webservice/' + @protocol + '/server.php', params)

  JSON.parse(response)
end