Class: PagarMe::Model

Inherits:
PagarMeObject show all
Defined in:
lib/pagarme/model.rb

Constant Summary

Constants inherited from PagarMeObject

PagarMeObject::RESOURCES

Instance Attribute Summary

Attributes inherited from PagarMeObject

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from PagarMeObject

#==, #[]=, convert, #empty?, #initialize, #respond_to?, #to_hash, #to_s, #unsaved_attributes

Constructor Details

This class inherits a constructor from PagarMe::PagarMeObject

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class PagarMe::PagarMeObject

Class Method Details

.all(*args, **params) ⇒ Object Also known as: where



39
40
41
42
# File 'lib/pagarme/model.rb', line 39

def all(*args, **params)
  params = extract_page_count_or_params(*args, **params)
  find_by params
end

.class_nameObject



49
50
51
# File 'lib/pagarme/model.rb', line 49

def class_name
  self.name.split('::').last
end

.create(*args, &block) ⇒ Object



21
22
23
# File 'lib/pagarme/model.rb', line 21

def create(*args, &block)
  self.new(*args, &block).create
end

.extract_page_count_or_params(*args, **params) ⇒ Object



57
58
59
60
61
# File 'lib/pagarme/model.rb', line 57

def extract_page_count_or_params(*args, **params)
  params[:page]  ||= args[0] || 1
  params[:count] ||= args[1] || 10
  params
end

.find_by(params = Hash.new, page = nil, count = nil) ⇒ Object Also known as: find_by_hash

Raises:



31
32
33
34
35
36
# File 'lib/pagarme/model.rb', line 31

def find_by(params = Hash.new, page = nil, count = nil)
  params = extract_page_count_or_params(page, count, **params)
  raise RequestError.new('Invalid page count') if params[:page] < 1 or params[:count] < 1

  PagarMe::Request.get(url, params: params).call
end

.find_by_id(id) ⇒ Object Also known as: find

Raises:



25
26
27
28
# File 'lib/pagarme/model.rb', line 25

def find_by_id(id)
  raise RequestError.new('Invalid ID') unless id.present?
  PagarMe::Request.get(url id).call
end

.underscored_class_nameObject



53
54
55
# File 'lib/pagarme/model.rb', line 53

def underscored_class_name
  class_name.gsub(/[a-z0-9][A-Z]/){|s| "#{s[0]}_#{s[1]}"}.downcase
end

.url(*params) ⇒ Object



45
46
47
# File 'lib/pagarme/model.rb', line 45

def url(*params)
  ["/#{ CGI.escape underscored_class_name }s", *params].join '/'
end

Instance Method Details

#createObject



4
5
6
7
# File 'lib/pagarme/model.rb', line 4

def create
  update PagarMe::Request.post(self.class.url, params: to_hash).run
  self
end

#saveObject



9
10
11
12
# File 'lib/pagarme/model.rb', line 9

def save
  update PagarMe::Request.put(url, params: unsaved_attributes).run
  self
end

#url(*params) ⇒ Object

Raises:



14
15
16
17
# File 'lib/pagarme/model.rb', line 14

def url(*params)
  raise RequestError.new('Invalid ID') unless id.present?
  self.class.url CGI.escape(id.to_s), *params
end