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
|
# File 'lib/mongo/model/conversion.rb', line 24
def to_rson options = {}, &block
options = {profile: options} if options.is_a? Symbol
if profile = options[:profile]
raise "no other optins are allowed when using :profile option!" if options.size > 1
meta = self.class.profiles[profile] || raise("profile :#{profile} not defined for #{self.class}!")
profile_options, profile_block = meta
to_rson profile_options.merge(_profile: profile), &profile_block
else
options.validate_options! :only, :except, :methods, :errors, :id, :_profile
child_options = options[:_profile] ? {profile: options[:_profile]} : {}
instance_variables = self.persistent_instance_variable_names
if only = options[:only]
instance_variables &= Array(only).collect{|n| :"@#{n}"}
elsif except = options[:except]
instance_variables -= Array(except).collect{|n| :"@#{n}"}
end
result = {}
instance_variables.each do |iv_name|
value = instance_variable_get iv_name
result[iv_name[1.. -1].to_sym] = value.to_rson child_options
end
methods = options[:methods] ? Array(options[:methods]) : []
methods.each do |method|
value = send method
result[method.to_sym] = value.to_rson child_options
end
with_errors = options.include?(:errors) ? options[:errors] : true
if with_errors and !(errors = self.errors).empty?
errors = {}
self.errors.each{|k, v| errors[k.to_sym] = v}
result[:errors] = errors
end
result[:id] = id if id and (options[:id] != false)
instance_exec result, &block if block
result
end
end
|