summaryrefslogtreecommitdiffstats
path: root/lib/hcl/day_entry.rb
blob: c4e24f459ac14a9bfcf1cc5c0e5d9f603fdfae15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'rexml/document'

class HCl
  class TimesheetResource
    def self.configure opts = nil
      if opts
        self.login = opts['login']
        self.password = opts['password']
        self.subdomain = opts['subdomain']
      else
        yield self
      end
    end
  
    # configuration accessors
    %w[ login password subdomain ].each do |config_var|
      class_eval <<-EOC
        def self.#{config_var}= arg
          @@#{config_var} = arg
        end
        def self.#{config_var}
          @@#{config_var}
        end
      EOC
    end
  
    def initialize params
      @data = params
    end
  
    def self.perform action
      client = Curl::Easy.new("https://#{subdomain}.harvestapp.com/#{action}")
      client.headers['Accept'] = 'application/xml'
      client.headers['Content-Type'] = 'application/xml'
      client.http_auth_types = Curl::CURLAUTH_BASIC
      client.userpwd = "#{login}:#{password}"
      if client.http_get
        client.body_str
      else
        raise "failed"
      end
    end
  
    def method_missing method, *args
      if @data.key? method.to_sym
        @data[method]
      else
        super
      end
    end
  end
  
  class DayEntry < TimesheetResource
    def self.all
      doc = REXML::Document.new perform('daily')
      doc.root.elements.collect('day_entries/day_entry') do |day|
        new(
          day.elements.map { |e| e.name }.inject({}) do |a, f|
            a[f.to_sym] = day.elements[f].text if day.elements[f]
            a
          end
        )
      end
    end
  end
end