Module: PayPal::Common::Base

Instance Method Summary collapse

Instance Method Details

#after_initializeObject



14
15
# File 'lib/paypal/common/base.rb', line 14

def after_initialize
end

#build_datetime(value) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/paypal/common/base.rb', line 33

def build_datetime(value)
  if value.respond_to?(:to_time)
    value.to_time
  else
    Time.parse(value.to_s)
  end
rescue
end

#build_value(klass, value) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/paypal/common/base.rb', line 21

def build_value(klass, value)
  if value.is_a?(Hash)
    klass.new(value)
  elsif value.is_a?(Array)
    value.map do |val|
      val.is_a?(Hash) ? klass.new(val) : val
    end
  else
    value
  end
end

#camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) ⇒ Object



76
77
78
79
80
81
82
# File 'lib/paypal/common/base.rb', line 76

def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
  else
    lower_case_and_underscored_word.to_s[0] + camelize(lower_case_and_underscored_word.to_s)[1..-1]
  end
end

#hash_keysObject



42
43
44
# File 'lib/paypal/common/base.rb', line 42

def hash_keys
  {}
end

#initialize(attributes = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
# File 'lib/paypal/common/base.rb', line 2

def initialize(attributes = {})
  attributes.each do |name, value|
    attr_name = underscore(name)
    if respond_to?("set_#{attr_name}") and (value.is_a?(Hash) or value.is_a?(Array))
      send("set_#{attr_name}", value)
    elsif respond_to?("#{attr_name}=")
      send("#{attr_name}=", value)
    end
  end
  after_initialize
end

#requestObject



17
18
19
# File 'lib/paypal/common/base.rb', line 17

def request
  PayPal::Common::Request.new
end

#to_hash(*args) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/paypal/common/base.rb', line 46

def to_hash(*args)
  ivars = args.empty? ? instance_variables : instance_variables.select { |var| args.include?(var[1..-1].to_sym) }
  Hash[
    ivars.map do |var|
      val = instance_variable_get(var)
      if val.is_a?(Array)
        val.map! { |a| a.respond_to?(:to_hash) ? a.to_hash : a }
      elsif val.respond_to?(:iso8601)
        val = val.iso8601
      else
        val = val.to_hash if val.respond_to?(:to_hash)
      end
      hash_key = hash_keys[var[1..-1].to_sym] || camelize(var[1..-1], false).to_sym
      [hash_key, val]
    end
  ]
end

#to_json(*args) ⇒ Object



64
65
66
# File 'lib/paypal/common/base.rb', line 64

def to_json(*args)
  MultiJson.dump(to_hash(*args))
end

#underscore(word) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/paypal/common/base.rb', line 68

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