Class: Freshdesk

Inherits:
Object
  • Object
show all
Defined in:
lib/freshdesk.rb

Defined Under Namespace

Classes: AlreadyExistedError, ConnectionError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url, username, password = 'X') ⇒ Freshdesk

Returns a new instance of Freshdesk.



13
14
15
16
17
18
19
20
# File 'lib/freshdesk.rb', line 13

def initialize(base_url, username, password='X')

  @base_url = base_url

  RestClient.add_before_execution_proc do | req, params |
    req.basic_auth username, password
  end
end

Instance Attribute Details

#base_urlObject

Returns the value of attribute base_url.



11
12
13
# File 'lib/freshdesk.rb', line 11

def base_url
  @base_url
end

Class Method Details

.fd_define_delete(name) ⇒ Object

Freshdesk API client support “DELETE” with the required id parameter



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/freshdesk.rb', line 89

def self.fd_define_delete(name)
  name = name.to_s
  method_name = "delete_" + name

  define_method method_name do |args|
    uri = mapping(name)
    raise StandardError, "An ID is required to delete" if args.size.eql? 0
    uri.gsub!(/.xml/, "/#{args}.xml")
    RestClient.delete uri
  end
end

.fd_define_get(name) ⇒ Object

Freshdesk API client support “GET” with id parameter optional

Returns nil if there is no response


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
# File 'lib/freshdesk.rb', line 37

def self.fd_define_get(name)
  name = name.to_s
  method_name = "get_" + name

  define_method method_name do |*args|
    uri = mapping(name)
    uri.gsub!(/\.xml/, "\.#{response_format}")

    # If we've been passed a string paramter, it means we're fetching
    # something like domain_URL/helpdesk/tickets/[ticket_id].xml
    #
    # If we're supplied with a hash parameter, it means we're fetching
    # something like domain_URL/helpdesk/tickets.xml?filter_name=all_tickets&page=[value]
    if args.size > 0
      url_args = args.first
      if url_args.class == Hash
        uri += '?' + URI.encode_www_form(url_args)
      else
        uri.gsub!(/\.#{response_format}/, "/#{url_args}\.#{response_format}")
      end
    end

    begin
      response = RestClient.get uri
    rescue Exception
      response = nil
    end
  end
end

.fd_define_parameterized_get(name) ⇒ Object

Certain GET calls require query strings instead of a more RESTful URI. This method and fd_define_get are mutually exclusive.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/freshdesk.rb', line 69

def self.fd_define_parameterized_get(name)
  name = name.to_s
  method_name = "get_" + name

  define_method method_name do |params={}|
    uri = mapping(name)
    uri.gsub!(/\.xml/, ".#{response_format}")
    unless params.empty?
      uri += '?' + URI.encode_www_form(params)
    end

    begin
      response = RestClient.get uri
    rescue Exception
      response = nil
    end
  end
end

.fd_define_post(name) ⇒ Object

Freshdesk API client support “POST” with the optional key, value parameter

Will throw:
  AlreadyExistedError if there is exact copy of data in the server
  ConnectionError     if there is connection problem with the server


106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/freshdesk.rb', line 106

def self.fd_define_post(name)
  name = name.to_s
  method_name = "post_" + name

  define_method method_name do |args, id=nil|
    raise StandardError, "Arguments are required to modify data" if args.size.eql? 0
    uri = mapping(name, id)

    builder = Nokogiri::XML::Builder.new do |xml|
      xml.send(doc_name(name)) {
        if args.has_key? :attachment
          attachment_name = args[:attachment][:name] or raise StandardError, "Attachment name required"
          attachment_cdata = args[:attachment][:cdata] or raise StandardError, "Attachment CDATA required"
          xml.send("attachments", type: "array") {
            xml.send("attachment") {
              xml.send("resource", "type" => "file", "name" => attachment_name, "content-type" => "application/octet-stream") {
                xml.cdata attachment_cdata
              }
            }
          }
        args.except! :attachment
        end
        args.each do |key, value|
          xml.send(key, value)
        end
      }
    end

    begin
      response = RestClient.post uri, builder.to_xml, :content_type => "text/xml"

    rescue RestClient::UnprocessableEntity
      raise AlreadyExistedError, "Entry already existed"

    rescue RestClient::InternalServerError
      raise ConnectionError, "Connection to the server failed. Please check hostname"

    rescue RestClient::Found
      raise ConnectionError, "Connection to the server failed. Please check username/password"

    rescue Exception
      raise
    end

    response
  end
end

.fd_define_put(name) ⇒ Object

Freshdesk API client support “PUT” with key, value parameter

Will throw:
  ConnectionError     if there is connection problem with the server


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/freshdesk.rb', line 158

def self.fd_define_put(name)
  name = name.to_s
  method_name = "put_" + name

  define_method method_name do |args|
    raise StandardError, "Arguments are required to modify data" if args.size.eql? 0
    raise StandardError, "id is required to modify data" if args[:id].nil?
    uri = mapping(name)

    builder = Nokogiri::XML::Builder.new do |xml|
      xml.send(doc_name(name)) {
        args.each do |key, value|
          xml.send(key, value)
        end
      }
    end

    begin
      uri.gsub!(/.xml/, "/#{args[:id]}.xml")
      response = RestClient.put uri, builder.to_xml, :content_type => "text/xml"

    rescue RestClient::InternalServerError
      raise ConnectionError, "Connection to the server failed. Please check hostname"

    rescue RestClient::Found
      raise ConnectionError, "Connection to the server failed. Please check username/password"

    rescue Exception
      raise
    end

    response
  end
end

Instance Method Details

#doc_name(name) ⇒ Object

match with the root name of xml document that freskdesk uses



227
228
229
230
231
232
233
234
235
236
# File 'lib/freshdesk.rb', line 227

def doc_name(name)
  case name
    when "tickets" then "helpdesk_ticket"
    when "ticket_fields" then "helpdesk-ticket-fields"
    when "ticket_notes" then "helpdesk_note"
    when "users" then "user"
    when "companies" then "customer"
    else raise StandardError, "No root object for this call"
  end
end

#mapping(method_name, id = nil) ⇒ Object

Mapping of object name to url:

tickets => helpdesk/tickets.xml
ticket_fields => /ticket_fields.xml
users => /contacts.xml
forums => /categories.xml
solutions => /solution/categories.xml
companies => /customers.xml


212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/freshdesk.rb', line 212

def mapping(method_name, id = nil)
  case method_name
    when "tickets" then File.join(@base_url + "helpdesk/tickets.xml")
    when "user_ticket" then File.join(@base_url + "helpdesk/tickets/user_ticket.xml")
    when "ticket_fields" then File.join(@base_url, "ticket_fields.xml")
    when "ticket_notes" then File.join(@base_url, "helpdesk/tickets/#{id}/notes.xml")
    when "users" then File.join(@base_url, "contacts.xml")
    when "forums" then File.join(@base_url + "categories.xml")
    when "solutions" then File.join(@base_url + "solution/categories.xml")
    when "companies" then File.join(@base_url + "customers.xml")
    when "time_sheets" then File.join(@base_url + "helpdesk/time_sheets.xml")
  end
end

#response_formatObject



22
23
24
# File 'lib/freshdesk.rb', line 22

def response_format
  @response_format ||= "xml"
end

#response_format=(format) ⇒ Object

Specify the response format to use–JSON or XML. Currently JSON is only supported for GETs, so other verbs will still use XML.



28
29
30
31
32
33
# File 'lib/freshdesk.rb', line 28

def response_format=(format)
  unless format.downcase =~ /json|xml/
    raise StandardError "Unsupported format: '#{format}'. Please specify 'xml' or 'json'."
  end
  @response_format = format.downcase
end