class RedcapAPI

Constants

DEFAULT_PARAMS
VERSION

Public Class Methods

new(token, url, parser = JSON) click to toggle source
# File lib/RedcapAPI.rb, line 29
def initialize(token, url, parser = JSON)
  @url     = url
  @payload = DEFAULT_PARAMS
  @payload[:token] = token
  @parser  = parser
end

Public Instance Methods

api(params = {}) click to toggle source
# File lib/RedcapAPI.rb, line 98
def api(params = {})
  payload = @payload.merge(params)
  return Mechanize.new.post(@url, payload).body
end
export(params = {}) click to toggle source
# File lib/RedcapAPI.rb, line 85
def export(params = {})
  return @parser.parse(api(params))
end
export_metadata(params = {}) click to toggle source
# File lib/RedcapAPI.rb, line 89
def export_metadata(params = {})
  payload = {:content => 'metadata'}.merge(params)
  return self.export(payload)
end
filter_data(data) click to toggle source
# File lib/RedcapAPI.rb, line 57
def filter_data(data)
  data = [data] if data.class == Hash

  data = data.collect do |entry|
    entry.each do |k, v|
      if v.class == Date
        entry[k] = v.strftime('%F')
      end
    end
  
    if !(entry.keys.include? 'record_id' or entry.keys.include? :record_id) # new entry and no id listed
      entry['record_id'] = next_open_record_id
    end
    entry
  end

end
get(record_id = nil) click to toggle source
# File lib/RedcapAPI.rb, line 36
def get(record_id = nil)
  data = self.export()
  if record_id
    data = data.select{|x| x['record_id'] == record_id.to_s}
  end
  data
end
get_fields() click to toggle source
# File lib/RedcapAPI.rb, line 44
def get_fields
  response = export_metadata()
  if response
    response.collect {|r| r['field_name'] if r }
  end
end
import(params = {}) click to toggle source
# File lib/RedcapAPI.rb, line 94
def import(params = {})
  return api(params)
end
next_open_record_id() click to toggle source
# File lib/RedcapAPI.rb, line 75
def next_open_record_id
  old_entries = self.get
  if old_entries.empty?
    '1'
  else
    max_entry = old_entries.max_by{|e| e['record_id'].to_i}['record_id']
    (max_entry.to_i + 1).to_s
  end
end
post(data) click to toggle source
# File lib/RedcapAPI.rb, line 51
def post(data)
  data = filter_data(data)
  data_string = data.to_json
  return self.import({:data => data_string})
end