Created
November 10, 2011 22:31
-
-
Save joegaudet/1356473 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'net/http' | |
| class Record | |
| include ActiveModel::Naming | |
| include ActiveModel::Validations | |
| include ActiveModel::Conversion | |
| attr_accessor :guid | |
| def id | |
| @id | |
| end | |
| def to_key | |
| @keys | |
| end | |
| def to_model | |
| self | |
| end | |
| def to_param | |
| id | |
| end | |
| def persisted? | |
| id != "" | |
| end | |
| def save | |
| end | |
| #class methods | |
| def self.initialize | |
| descendant.instance_variable_set(:@keys, keys.dup) | |
| end | |
| def self.find(id) | |
| res = Plato.connection.get("#{@base_url}/#{id}", {"Cookie" => "MatygoSession=#{Plato.session_string}"}) | |
| begin | |
| res.value # raises error if not 200 | |
| rescue Net::HTTPServerException | |
| puts "REsponse wasn't 200" | |
| end | |
| instance = self.new | |
| json = ActiveSupport::JSON.decode(res.body)["content"] # unwrap content | |
| instance.from_json(instance, json) | |
| end | |
| def self.all | |
| res = Plato.connection.get("#{@base_url}", {"Cookie" => "MatygoSession=#{Plato.session_string}"}) | |
| begin | |
| res.value # raises error if not 200 | |
| rescue Net::HTTPServerException | |
| puts "REsponse wasn't 200" | |
| end | |
| retval = Array.new | |
| json = ActiveSupport::JSON.decode(res.body)["content"] # unwrap content | |
| json.each do |element| | |
| instance = self.from_json(self.new, element) | |
| puts instance | |
| retval << instance | |
| end | |
| retval | |
| end | |
| def self.from_json(instance, json) | |
| instance.instance_variable_set("@id", json["guid"]) | |
| self.keys.each do |k| | |
| temp_k = k.to_s.camelize | |
| key = temp_k[0, 1].downcase + temp_k[1..-1] | |
| instance.instance_variable_set("@#{k}", json[key]) | |
| end | |
| instance | |
| end | |
| def self.base_url(url) | |
| @base_url = url | |
| end | |
| def self.keys | |
| @keys ||= [] | |
| end | |
| def self.key(*key_names) | |
| key_names.each do |m| | |
| keys << m | |
| define_method(m) do | |
| instance_variable_get("@#{m}") | |
| end | |
| define_method("#{m}=") do |val| | |
| instance_variable_set("@#{m}",val) | |
| end | |
| end | |
| keys.uniq! | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment