7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
|
# File 'lib/restful/converters/active_record.rb', line 7
def self.convert(model, config, options = {})
published = []
nested = config.nested?
resource = Restful.resource(
model.class.to_s.tableize.demodulize.singularize, {
:base => Restful::Rails.api_hostname,
:path => model.restful_path,
:url => model.restful_url
})
resource.values += Restful::Rails.tools.simple_attributes_on(model).map do |key, value|
convert_to_simple_attribute(key, value, config, published, model)
end.compact
resource.values += model.class.reflections.keys.map do |key|
if config.published?(key.to_sym)
nested_config = config.nested(key.to_sym)
published << key.to_sym
if model.class.reflections[key].macro == :has_many && !nested
convert_to_collection(model, key, nested_config, published) do |key, resources, extended_type|
Restful.collection(key, resources, extended_type)
end
elsif model.class.reflections[key].macro == :has_one or model.class.reflections[key].macro == :belongs_to
if(config.expanded?(key, nested))
convert_to_collection(model, key, nested_config, published) do |key, resources, extended_type|
returning(resources.first) do |res|
res.name = key
end
end
else
value = model.send(key)
restful_path = value ? value.restful_path : nil
basename = value ? Restful::Rails.api_hostname : nil
Restful.link("#{ key }-restful-url", basename, restful_path, compute_extended_type(model, key))
end
end
end
end.compact
if model.class.apiable_association_table
resource.values += model.class.apiable_association_table.keys.map do |key|
if config.published?(key.to_sym)
published << key.to_sym
base, path = model.resolve_association_restful_url(key)
Restful.link(key.to_sym, base, path, compute_extended_type(model, key))
end
end.compact
end
resource.values += (model.public_methods - Restful::Rails.tools.simple_attributes_on(model).keys.map(&:to_s)).map do |method_name|
if config.published?(method_name.to_sym) and not published.include?(method_name.to_sym)
value = model.send(method_name.to_sym)
sanitized_method_name = method_name.tr("!?", "").tr("_", "-").to_sym
if value.is_a? ::ActiveRecord::Base
if config.expanded?(method_name.to_sym, nested)
returning Restful::Rails.tools.expand(value, config.nested(method_name.to_sym)) do |expanded|
expanded.name = sanitized_method_name
end
else
Restful.link("#{ sanitized_method_name }-restful-url", Restful::Rails.api_hostname, value ? value.restful_path : "", compute_extended_type(model, key))
end
else
Restful.attr(sanitized_method_name, value, compute_extended_type(model, method_name))
end
end
end.compact
resource
end
|