Module: Kobana::Resources::Operations::ClassMethods
- Defined in:
- lib/kobana/resources/operations.rb
Instance Method Summary collapse
- #all(params = {}) ⇒ Object
- #create(attributes = {}, options = {}) ⇒ Object
- #find(resource_id, params = {}) ⇒ Object
- #find_by(params = {}, options = {}) ⇒ Object
- #find_or_create_by(params, attributes = {}, options = {}) ⇒ Object
- #handle_error_response(response) ⇒ Object
Instance Method Details
#all(params = {}) ⇒ Object
11 12 13 14 15 16 17 18 19 20 |
# File 'lib/kobana/resources/operations.rb', line 11 def all(params = {}) response = request(:get, uri(params), params) case response[:status] when 200 response[:data].map { |data| new(data) } else handle_error_response(response) [] end end |
#create(attributes = {}, options = {}) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/kobana/resources/operations.rb', line 34 def create(attributes = {}, = {}) response = request(:post, uri(attributes), attributes, ) case response[:status] when 201 new(response[:data].merge(created: true)) else handle_error_response(response) resource = new(attributes.merge(created: false)) resource.errors = @errors resource end end |
#find(resource_id, params = {}) ⇒ Object
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/kobana/resources/operations.rb', line 47 def find(resource_id, params = {}) response = request(:get, "#{uri(params)}/#{resource_id}", params) case response[:status] when 200 new(response[:data]) else handle_error_response(response) nil end end |
#find_by(params = {}, options = {}) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/kobana/resources/operations.rb', line 22 def find_by(params = {}, = {}) result = all(params) return nil if result.empty? || (result.size > 1 && [:ignore_multiple]) match = params.all? do |key, value| result.first[key] == value end return unless match result.first end |
#find_or_create_by(params, attributes = {}, options = {}) ⇒ Object
58 59 60 61 62 63 64 65 |
# File 'lib/kobana/resources/operations.rb', line 58 def find_or_create_by(params, attributes = {}, = {}) = { ignore_multiple: false, find_by_id: false, find_params: nil }.merge() if [:find_by_id] find(params, [:find_params]) || create(attributes) else find_by(params, ) || create(attributes.merge(params.deep_symbolize_keys), ) end end |
#handle_error_response(response) ⇒ Object
67 68 69 70 71 72 |
# File 'lib/kobana/resources/operations.rb', line 67 def handle_error_response(response) return unless response[:data].is_a?(Hash) @errors = response[:data][:errors] if response[:data].key?(:errors) @errors = [{ title: response[:data][:error] }] if response[:data].key?(:error) end |