Module: Restful::Rails::ActiveRecord::MetadataTools::Utils

Defined in:
lib/restful/rails/active_record/metadata_tools.rb

Class Method Summary collapse

Class Method Details

.convert_collection_to_resources(model, key, config) ⇒ Object

Takes an ar model and a key like :people, and returns an array of resources.

TODO: don't load the entire association, only the published attributes (with an appropriate :select). 
TODO: get some pagination in.


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/restful/rails/active_record/metadata_tools.rb', line 82

def self.convert_collection_to_resources(model, key, config)
  
  # load the associated objects.
  models = model.send(key)
  
  # convert them to_restful. 
  if models
    [*models].map do |m| 
      if m.respond_to? :to_restful
        config.nested? ?
          link(key, m, config) :
          expand(m, config)
      else
        raise "Seems as if you want to export the relation #{ key } of an #{ model.class.to_s } object without making #{ key } apiable."
      end
    end
  end
end

.dereference(url) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/restful/rails/active_record/metadata_tools.rb', line 56

def self.dereference(url)
  regexp = Regexp.new("#{ Restful::Rails.api_hostname }\/(.*)\/(.*)")
  m, resource, params = *url.match(regexp)
  resource = if resource && params
    clazz = resource.try(:singularize).try(:camelize).try(:constantize)
    clazz.find_by_restful(params) if clazz 
  end

  resource ? resource.id : 0
end

.expand(resource, config) ⇒ Object

called for nested resources.



47
48
49
50
# File 'lib/restful/rails/active_record/metadata_tools.rb', line 47

def self.expand(resource, config)
  config.restful_options[:nested] = true
  resource.to_restful(config)
end


52
53
54
# File 'lib/restful/rails/active_record/metadata_tools.rb', line 52

def self.link(key, model, config)
  Restful.link(key.to_sym, "base", "path", "link")
end

.simple_attributes_on(model) ⇒ Object

retruns non association / collection attributes.



68
69
70
71
72
73
74
# File 'lib/restful/rails/active_record/metadata_tools.rb', line 68

def self.simple_attributes_on(model)
  attributes = model.attributes
  
  attributes.delete_if do |k, v|
    model.class.apiable_association_table && model.class.apiable_association_table.keys.include?(k)
  end
end