Class: Answers::BaseModel
- Inherits:
-
Object
- Object
- Answers::BaseModel
- Defined in:
- lib/answers/base_model.rb
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.all ⇒ Object
39 40 41 42 43 44 |
# File 'lib/answers/base_model.rb', line 39 def self.all response = Answers.client.get(Protocol.uri(resource_name)) items = response[hash_key] items.map {|i| new(i)} end |
.find(id) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/answers/base_model.rb', line 24 def self.find(id) response = Answers.client.get(Protocol.uri(resource_name, id)) if response.has_key?('status') if response['status'] return nil end end item_hash = response[hash_key].first item = new(item_hash) item end |
.hash_key ⇒ Object
16 17 18 |
# File 'lib/answers/base_model.rb', line 16 def self.hash_key self.resource_name.to_s.pluralize end |
.resource_name ⇒ Object
8 9 10 |
# File 'lib/answers/base_model.rb', line 8 def self.resource_name to_s.demodulize.downcase.to_sym end |
Instance Method Details
#delete ⇒ Object
59 60 61 62 63 64 |
# File 'lib/answers/base_model.rb', line 59 def delete raise Answers::Error.new("Cannot delete unsaved object.") if new? response = Answers.client.delete(Protocol.uri(resource_name, @id)) response end |
#hash_key ⇒ Object
20 21 22 |
# File 'lib/answers/base_model.rb', line 20 def hash_key self.class.hash_key end |
#new? ⇒ Boolean
4 5 6 |
# File 'lib/answers/base_model.rb', line 4 def new? @id.nil? end |
#resource_name ⇒ Object
12 13 14 |
# File 'lib/answers/base_model.rb', line 12 def resource_name self.class.resource_name end |
#save ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/answers/base_model.rb', line 46 def save body = attributes.delete_if {|k,v| v.nil?} path = new? ? Protocol.uri(resource_name) : Protocol.uri(resource_name, @id) method = new? ? :post : :put response = Answers.client.send(method, path, body) item_hash = response[hash_key].first update_attributes!(item_hash) self end |