Module: Mongo::Model::Conversion

Defined in:
lib/mongo/model/conversion.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#model_to_json(*args, &block) ⇒ Object Also known as: to_json



4
5
6
# File 'lib/mongo/model/conversion.rb', line 4

def model_to_json *args, &block
  to_rson(*args, &block).to_json
end

#model_to_xml(*args, &block) ⇒ Object Also known as: to_xml



8
9
10
# File 'lib/mongo/model/conversion.rb', line 8

def model_to_xml *args, &block
  to_rson(*args, &block).to_xml
end

#to_rson(options = {}, &block) ⇒ Object



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
      # value = convert_object value, :to_rson, child_options
      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
      # value = convert_object value, :to_rson, child_options
      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