summaryrefslogtreecommitdiff
path: root/lib/extensions/couchrest.rb
blob: 1734f3bd72eafe2fc6af9eb634206869b20ce648 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
module CouchRest
  module Model
    class Base
      extend ActiveModel::Naming
      extend ActiveModel::Translation
    end
    module Designs

      class View

        # so we can called Ticket.method.descending or Ticket.method.ascending
        def ascending
          self
        end
      end

      class DesignMapper
        DEFAULT_REDUCE = <<-EOJS
          function(key, values, rereduce) {
            return sum(values);
          }
          EOJS
        def load_views(dir, reduce=DEFAULT_REDUCE)
          Dir.glob("#{dir}/*.js") do |js|
            name = File.basename(js, '.js')
            file = File.open(js, 'r')
            view name.to_sym,
              map: file.read,
              reduce: reduce
          end
        end
      end
    end

    module Utils
      module Migrate
        def self.load_all_models_with_engines
          self.load_all_models_without_engines
          return unless defined?(Rails)
          Dir[Rails.root + 'engines/*/app/models/**/*.rb'].each do |path|
            require path
          end
        end

        class << self
          alias_method_chain :load_all_models, :engines
        end

        def dump_all_models
          prepare_directory
          find_models.each do |model|
            model.design_docs.each do |design|
              dump_design(model, design)
            end
          end
        end

        protected

        def dump_design(model, design)
          dir = prepare_directory model.name.tableize
          filename = design.id.sub('_design/','') + '.json'
          puts dir + filename
          design.checksum
          File.open(dir + filename, "w") do |file|
            file.write(JSON.pretty_generate(design.to_hash))
          end
        end

        def prepare_directory(dir = '')
          dir = Rails.root + 'tmp' + 'designs' + dir
          Dir.mkdir(dir) unless Dir.exist?(dir)
          return dir
        end

      end
    end

  end

end