Module: ApiModel::InstanceMethods
Instance Method Summary collapse
-
#property_exists?(property_name) ⇒ Boolean
Overrides Hashie::Trash to catch errors from trying to set properties which have not been defined and defines it automatically.
-
#save(path, body = nil, options = {}) ⇒ Object
Sends a request to the api to update a resource.
-
#set_errors_from_hash(errors_hash, obj = self) ⇒ Object
Convenience method to handle error hashes and set them as ActiveModel errors on instances.
Instance Method Details
#property_exists?(property_name) ⇒ Boolean
Overrides Hashie::Trash to catch errors from trying to set properties which have not been defined and defines it automatically
12 13 14 15 16 17 |
# File 'lib/api_model/instance_methods.rb', line 12 def property_exists?(property_name) super property_name rescue NoMethodError Log.debug "Could not set #{property_name} on #{self.class.name}. Defining it now." self.class.property property_name.to_sym end |
#save(path, body = nil, options = {}) ⇒ Object
Sends a request to the api to update a resource. If the response was successful, then it will update the instance with any changes which the API has returned. If not, it will set ActiveModel errors.
The default request type is PUT, but you can override this by setting :request_method
in the options hash.
It also includes 3 callbacks which you can hook onto; save
, which is the entire method, whether the API request was successful or not, and successful_save
and unsuccessful_save
which are triggered on successful or unsuccessful responses.
By default it uses the ApiModel::Builder::Hash
builder rather than using the normal method of using the class, or api config builders. This is to avoid building new objects from the response, but can be easily overriden by passing in :builder
in the options hash.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/api_model/instance_methods.rb', line 47 def save(path, body=nil, ={}) request_method = .delete(:request_method) || :put run_callbacks :save do response = self.class.call_api_with_json request_method, path, body, .reverse_merge(builder: ApiModel::Builder::Hash.new) response_success = response.http_response.api_call.success? if response_success run_callbacks :successful_save do update_attributes response.response_body end else run_callbacks :unsuccessful_save do set_errors_from_hash response.response_body["errors"] end end response_success end end |
#set_errors_from_hash(errors_hash, obj = self) ⇒ Object
Convenience method to handle error hashes and set them as ActiveModel errors on instances. Using the ‘obj`, you can move the errors on to child classes if needed.
21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/api_model/instance_methods.rb', line 21 def set_errors_from_hash(errors_hash, obj = self) errors_hash.each do |field,| if .is_a?(Array) .each do || obj.errors.add field.to_sym, end else obj.errors.add field.to_sym, end end end |