Module: Supr::Utils

Included in:
Client, Url
Defined in:
lib/supr/utils.rb

Instance Method Summary collapse

Instance Method Details

#attr_define(k, v) ⇒ Object



17
18
19
20
21
# File 'lib/supr/utils.rb', line 17

def attr_define(k,v)
  instance_variable_set("@#{k}", v)
  meta = class << self; self; end
  meta.class_eval { attr_reader k.to_sym }
end

#create_hash_from_url(url) ⇒ Object



13
14
15
# File 'lib/supr/utils.rb', line 13

def create_hash_from_url(url)
  url.gsub(/^.*(bit\.ly|j\.mp)\//,'')
end

#create_url(resource = "", args = {}) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/supr/utils.rb', line 35

def create_url(resource="",args={})
  args = args.merge({:login => @login, :apiKey => @api_key, :version => API_VERSION})
  url = URI.join(API_URL,resource)
  long_urls = args.delete(:long_urls)
  url.query = args.map { |k,v| "%s=%s" % [CGI.escape(k.to_s), CGI.escape(v.to_s)] }.join("&")
  url.query << "&" + long_urls.map { |long_url| "longUrl=#{CGI.escape(long_url)}" }.join("&") unless long_urls.nil?
  url
end

#get_result(request) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/supr/utils.rb', line 44

def get_result(request)
  begin
    json = Net::HTTP.get(request)
    # puts json.inspect
    result = Crack::JSON.parse(json)
  rescue
    result = {'errorMessage' => 'JSON Parse Error(Bit.ly messed up)', 'errorCode' => 69, 'statusCode' => 'ERROR'}
  end
  if result['statusCode'] == "OK"
    result = result['results']
  else
    raise SuprError.new(result['errorMessage'],result['errorCode'])
  end
end

#instance_variablise(obj, variables) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/supr/utils.rb', line 23

def instance_variablise(obj,variables)
  if obj.is_a? Hash
    obj.each do |k,v|
      if v.is_a? Hash
        instance_variablise(v,variables)
      else
        attr_define(underscore(k),v) if variables.include?(underscore(k))
      end
    end
  end
end

#underscore(camel_cased_word) ⇒ Object

stolen from rails



5
6
7
8
9
10
11
# File 'lib/supr/utils.rb', line 5

def underscore(camel_cased_word) # stolen from rails
  camel_cased_word.to_s.gsub(/::/, '/').
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end