Module: Restful::Rails::ActiveRecord::Configuration::CommonInstanceMethods
- Defined in:
- lib/restful/rails/active_record/configuration.rb
Instance Method Summary collapse
-
#to_restful(config = nil) ⇒ Object
converts this AR object to an apimodel object.
Instance Method Details
#to_restful(config = nil) ⇒ Object
converts this AR object to an apimodel object. per default, only the
attributes in self.class.restful_config are shown. this can be overriden
by passing in something like @pet.to_restful(:name, :species).
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/restful/rails/active_record/configuration.rb', line 38 def to_restful(config = nil) add_to_whitelist = [] if config && config.is_a?(Hash) && config.keys.size == 1 && includes = config[:include] add_to_whitelist = [*includes].map { |el| el.is_a?(String) ? el.to_sym : el } config = nil end config ||= self.class.restful_config.clone if self.class.respond_to?(:restful_config) config ||= [] if config && !config.is_a?(Config) config = Config.new(config) end if self.class.respond_to?(:restful_config) config.whitelisted = Array.new(self.class.restful_config.whitelisted) if config.whitelisted.empty? config..merge! self.class.restful_config. end config.whitelisted += add_to_whitelist config.whitelisted = config.whitelisted.uniq # array if self.is_a?(Array) elements = self.map do |el| raise TypeError.new("Not all array elements respond to #to_restful. ") unless el.respond_to?(:to_restful) Restful::Converters::ActiveRecord.convert(el, el.class.restful_config) end element_name = elements.first ? elements.first.name.pluralize : "nil-classes" returning Restful.collection(element_name, elements, :array) do |collection| collection.total_entries = self.total_entries if self.respond_to?(:total_entries) end elsif self.is_a?(Hash) elements = self.map do |k,v| if v.respond_to?(:to_restful) and v.class.respond_to?(:restful_config) value = Restful::Converters::ActiveRecord.convert(v, v.class.restful_config) else value = v.respond_to?(:to_restful) ? v.to_restful : v end Restful::ApiModel::Attribute.new(k, value, :map) end map = Restful::ApiModel::Map.new("hash") map.values = elements map else Restful::Converters::ActiveRecord.convert(self, config) end end |