Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - How do I DRY up my CouchDB views?

What can I do to share code among views in CouchDB?

Example 1 -- utility methods

Jesse Hallett has some good utility methods, including

function dot(attr) {
  return function(obj) {
      return obj[attr];
  }
}

Array.prototype.map = function(func) {
  var i, r = [],
  for (i = 0; i < this.length; i += 1) {
    r[i] = func(this[i]);
  }
  return r;
};

...

Where can I put this code so every view can access it?

Example 2 -- constants

Similarly for constants I use in my application. Where do I put

MyApp = {
  A_CONSTANT = "...";
  ANOTHER_CONSTANT = "...";
};

Example 3 -- filter of a filter:

What if I want a one view that filters by "is this a rich person?":

function(doc) {
  if (doc.type == 'person' && doc.net_worth > 1000000) {
    emit(doc.id, doc);
  }
}

and another that indexes by last name:

function(doc) {
  if (doc.last_name) {
    emit(doc.last_name, doc);
  }
}

How can I combine them into a "rich people by last name" view?

I sort of want the equivalent of the Ruby

my_array.select { |x| x.person? }.select { |x| x.net_worth > 1,000,000 }.map { |x| [x.last_name, x] }

How can I be DRYer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per this blog post, you can add commonjs modules to the map function (but not the reduce function) in views in couchdb 1.1 by having a key called lib in your views object. A lot of popular javascript libraries like underscore.js adhere to the commonjs standard, so you can use them in your views by using require("views/lib/[your module name]").

Say you include underscore.js as "underscore" in the lib object in views, like so:

views: {
    lib: {
         underscore: "// Underscore.js 1.1.6
 ...
    }
    ...
    [ the rest of your views go here]
}

, you can then add the following to your view to get access to the _ module:

var _ = require("views/lib/underscore");

For custom libraries, all you need to do is make anything you want to share in your library a value to the global "exports" object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...