summaryrefslogtreecommitdiff
path: root/core/lib/extensions/couchrest.rb
blob: 91dfc1c4beb38e0dbc9881ea56dd43c3af85fd19 (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
module CouchRest
  module Model
    module Designs

      class View

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

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

    module Errors
      class ConnectionFailed < CouchRestModelError; end
    end

    module Connection

      module ClassMethods

        def use_database(db)
          @database = prepare_database(db)
        rescue RestClient::Unauthorized,
          Errno::EHOSTUNREACH,
          Errno::ECONNREFUSED => e
          raise CouchRest::Model::Errors::ConnectionFailed.new(e.to_s)
        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 + 'app/models/**/*.rb'].each do |path|
            require path
          end
          Dir[Rails.root + '*/app/models/**/*.rb'].each do |path|
            require path
          end
        end

        def self.all_models_and_proxies
          callbacks = migrate_each_model(find_models)
          callbacks += migrate_each_proxying_model(find_proxying_models)
          cleanup(callbacks)
        end



        class << self
          alias_method_chain :load_all_models, :engines
        end

      end
    end
  end

  class ModelRailtie
    config.action_dispatch.rescue_responses.merge!(
      'CouchRest::Model::DocumentNotFound' => :not_found,
      'RestClient::ResourceNotFound' => :not_found
    )
  end
end