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



2
3
4
# File 'lib/mongo/model/conversion.rb', line 2

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

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



6
7
8
# File 'lib/mongo/model/conversion.rb', line 6

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

#to_hash(options = {}) ⇒ Object



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
# File 'lib/mongo/model/conversion.rb', line 22

def to_hash options = {}
  if profile = options[:profile]
    raise "no other optins are allowed when using :profile option!" if options.size > 1
    profile_options = self.class.profiles[profile] || raise("profile :#{profile} not defined for #{self.class}!")
    to_hash profile_options.merge(_profile: profile)
  else
    options.validate_options! :only, :except, :methods, :errors, :_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_model value, :to_hash, child_options
      result[iv_name[1.. -1].to_sym] = value
    end

    methods = options[:methods] ? Array(options[:methods]) : []
    methods.each do |method|
      value = send method
      value = convert_model value, :to_hash, child_options
      result[method.to_sym] = value
    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
  end
end