Module: SimplyCouch::Model::Ancestry

Included in:
ClassMethods
Defined in:
lib/simply_couch/model/ancestry.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, TreeBuilder

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ancestry_by_propertyObject



184
185
186
# File 'lib/simply_couch/model/ancestry.rb', line 184

def self.ancestry_by_property
  @ancestry_by_property
end

Instance Method Details

#has_ancestry(options = {}) ⇒ Object

Add ancestry logic to your model

class Page
  include SimplyCouch::Model
  has_ancestry
end

or

class Page
  include SimplyCouch::Model
  property :locale
  has_ancestry by_property: :locale
end


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/simply_couch/model/ancestry.rb', line 182

def has_ancestry(options = {})
  @ancestry_by_property = nil
  def self.ancestry_by_property
    @ancestry_by_property
  end
  options = {order_by: :position}.merge(options)
  order_by = case options[:order_by]
             when Symbol then "doc['#{options[:order_by]}']"
             when Array then "[#{options[:order_by].map{|o| "doc['#{o}']"}.join(', ')}]"
             else "doc['position']"
             end
  property :path_ids, type: Array, default: []
  property :position, type: Integer, default: 0
  if options[:by_property].present?
    property options[:by_property] unless property_names.include?(options[:by_property])
    @ancestry_by_property = options[:by_property]
    by_property_view_prefix = options[:by_property].present? ? "doc['#{options[:by_property]}'], " : ''
  end

  view :subtree_view, type: :custom, include_docs: true, map_function: %|function(doc){
    if(doc['ruby_class'] == '#{name}' && doc.path_ids){
      for(var i = 0; i < doc.path_ids.length - 1; i++){
        emit([#{by_property_view_prefix}doc.path_ids[i], #{order_by}], 1);
      }
    }
  }|, reduce_function: "_sum"

  view :children_view, type: :custom, include_docs: true, map_function: %|function(doc){
    if(doc['ruby_class'] == '#{name}' && doc.path_ids){
      emit([#{by_property_view_prefix}doc.path_ids.slice(-2,-1)[0], #{order_by}], 1);
    }
  }|, reduce_function: "_sum"
  view :roots_view, conditions: "doc.path_ids && doc.path_ids.length == 1", key: [options[:by_property].presence, options[:order_by]].compact
  include SimplyCouch::Model::Ancestry::InstanceMethods
  extend SimplyCouch::Model::Ancestry::ClassMethods
  before_update :update_tree_path
  after_create :create_tree_path
end