Class: SimplyCouch::Model::EmbeddedIn::Property

Inherits:
Object
  • Object
show all
Defined in:
lib/simply_couch/model/embedded_in.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner_clazz, name, options = {}) ⇒ Property

Returns a new instance of Property.



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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/simply_couch/model/embedded_in.rb', line 52

def initialize(owner_clazz, name, options = {})
  @name = name
  embedded_in_name = name
  @options = {
    :class_name => name.to_s.singularize.camelize
  }.update(options)

  @options.assert_valid_keys(:class_name)

  # For now restrictions on naming
  parent_property_name = owner_clazz.name.property_name.pluralize

  owner_clazz.class_eval do
    property :"#{name}_id"
    attr_accessor :parent_object
    property :index
    @@embedded_in_class_name = name.to_s.camelize

    class << self

      define_method :embedded_in_class_name do
      #  embedded_in_name.to_s.singularize.camelize
        @@embedded_in_class_name
      end

      define_method :belongs_to do |belongs_to_name, *args|
        super(*([belongs_to_name] + args))
        # Now override belongs to view
        view "association_#{foreign_property}_belongs_to_#{belongs_to_name}",
          :map_function => %|function(doc){if(doc['ruby_class'] == '#{embedded_in_class_name}' && doc['#{self.name.property_name.pluralize}']){
            for(var i in doc.#{self.name.property_name.pluralize}){
              if(doc['#{self.name.property_name.pluralize}'][i]['#{belongs_to_name.to_s.foreign_key}']){
                emit([doc['#{self.name.property_name.pluralize}'][i]['#{belongs_to_name.to_s.foreign_key}'], doc['created_at']], doc['#{self.name.property_name.pluralize}'][i]);
              }
            }
          }}|,
          :reduce_function => %|function(key, values){return values.length}|,
          :type => :raw,
          :results_filter => lambda{|results| results['rows'].map{|row| d = row['value']; d.parent_object = row['doc']; d.parent_object.send(self.name.property_name.pluralize)[d.index]}},
          :include_docs => true
      end

      define_method :count do |options = {}|
        database.view(all_documents_for_count(options.merge(:reduce => true)))['rows'].try(:first).try('[]', 'value').to_i
      end
    end

    # Make parent object send through original for callbacks
    define_method :parent_object= do |value|
      return @parent_object if @parent_object && @parent_object == value
      @parent_object = value # Prevent circular calls
      send("#{name}=", value)
    end
    # Redefine the equality method, since we are different kind of objects
    define_method "==" do |value|
      self.class == value.class && (value.respond_to?(:parent_object) && self.parent_object == value.parent_object) && (value.respond_to?(:index) && self.index == value.index)
    end
    view :all_documents_for_count, :type => :raw, :include_docs => false, :map_function => %|function(doc){
      if(doc['ruby_class'] == '#{name.to_s.singularize.camelize}' && typeof(doc['#{parent_property_name}']) == 'object'){
        for(var i=0; i < doc['#{parent_property_name}'].length; i++){
          emit(doc['#{parent_property_name}'][i]['created_at'], 1);
        }
      }
    }|, :reduce_function => '_sum'
    view :all_documents, :type => :raw, :include_docs => true, :map_function => %|function(doc){
      if(doc['ruby_class'] == '#{name.to_s.singularize.camelize}' && typeof(doc['#{parent_property_name}']) == 'object'){
        for(var i=0; i < doc['#{parent_property_name}'].length; i++){
          emit(doc['#{parent_property_name}'][i]['created_at'], doc['#{parent_property_name}'][i]);
        }
      }
    }|, :results_filter => lambda{|results| results['rows'].map{|row| d = row['value']; d.parent_object = row['doc']; d.parent_object.send(parent_property_name)[d.index]}}



    # For now empty merge. Since value of map function is transformed to object
    define_method :merge do |*args|
    end

    define_method :save do |callbacks=true|
      if !parent_object
        errors.add(name, 'no_parent')
        return false
      end
      if callbacks
        _run_save_callbacks do
          parent_object.is_dirty if self.dirty?
          parent_object.save
        end
      else
        parent_object.is_dirty if self.dirty?
        parent_object.save
      end
    end

    define_method name do |*args|
      local_options = args.last.is_a?(Hash) ? args.last : {}
      local_options.assert_valid_keys(:force_reload, :with_deleted)
      forced_reload = local_options[:force_reload] || false
      with_deleted = local_options[:with_deleted] || false
      return parent_object
    end

    define_method "#{name}=" do |value|
      return value if instance_variable_get("@#{name}") == value
      klass = self.class.get_class_from_name(name)
      raise ArgumentError, "expected #{klass} got #{value.class}" unless value.nil? || value.is_a?(klass)

      if value
        # Has many object update
        value_has_many_name = klass.properties.find{|p| p.is_a?(SimplyCouch::Model::HasManyEmbedded::Property) && p.options[:class_name] == self.class.name}.try(:name)
        value.send("add_#{value_has_many_name.to_s.singularize}", self) unless !value_has_many_name || value.send(value_has_many_name).include?(self)

        # Has one object update
        #value_has_one_name = klass.properties.find{|p| p.is_a?(SimplyCouch::Model::HasOneEmbedded::Property) && p.options[:class_name] == self.class.name}.try(:name)
        #value.instance_variable_set("@#{value_has_one_name}", self) unless !value_has_one_name || value.send(value_has_one_name) == self
      end

      # Mark changed if appropriate
      send("#{name}_will_change!") if value != parent_object

      instance_variable_set('@parent_object', value)
      if value.nil?
        send("#{name}_id=", nil)
      else
        send("#{name}_id=", value.id)
      end
    end
  end
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



50
51
52
# File 'lib/simply_couch/model/embedded_in.rb', line 50

def name
  @name
end

#optionsObject

Returns the value of attribute options.



50
51
52
# File 'lib/simply_couch/model/embedded_in.rb', line 50

def options
  @options
end

Instance Method Details

#association?Boolean

Returns:

  • (Boolean)


190
191
192
# File 'lib/simply_couch/model/embedded_in.rb', line 190

def association?
  true
end

#build(object, json) ⇒ Object



181
182
183
# File 'lib/simply_couch/model/embedded_in.rb', line 181

def build(object, json)
  object.send "#{name}_id=", json["#{name}_id"]
end

#serialize(json, object) ⇒ Object Also known as: value



185
186
187
# File 'lib/simply_couch/model/embedded_in.rb', line 185

def serialize(json, object)
  json["#{name}_id"] = object.send("#{name}_id") if object.send("#{name}_id")
end