Sunday, September 30, 2012

Vocab App

Last week I developed an API to enable a client to connect to the system and pull a list of words and their definitions. The client program then runs a game and saves the results in the system.

I also wrote some ruby scripts to input the words and definitions into the system, also using the api.

require 'net/http'
require 'json'
require 'csv'

class Poster

  def initialize
  @words = URI('http://URL GOES HERE/words.json')
  @definitions = URI('http://URL GOES HERE/definitions.json')
  end

  def post_word name, difficulty
    res = Net::HTTP.post_form(@words,'word[name]' => name.encode('UTF-8'), 'word[difficulty]' => difficulty.encode('UTF-8'))
    JSON.parse(res.body)['id']
  end

  def post_definition word, body
    res = Net::HTTP.post_form(@definitions,'definition[word_id]' => word, 'definition[body]' => body.encode('UTF-8'))
    puts res.body
  end


end
poster = Poster.new

CSV.foreach(ARGV[0], {:headers => true, :header_converters => :symbol, :col_sep => "\t" }) do |row|
  poster.post_definition(poster.post_word(row[1],row[0]),row[2])
end


The Program goes through a CSV file that has the words, their definitions and their difficulty. It posts a word to the system and gets back a word_id, then it posts the definition passing it the corresponding word_id

No comments:

Post a Comment