Skip to content

Commit

Permalink
Add offset option to getLocaleFromUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
Ricardo Nogueira committed May 17, 2016
1 parent f8c2f93 commit 0e8dea3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,12 @@ Accept-Language: zh-CN,zh;q=0.5
Cookie: locale=zh-TW
```

#### ctx.getLocaleFromUrl(), ctx.request.getLocaleFromUrl()
#### ctx.getLocaleFromUrl(offset), ctx.request.getLocaleFromUrl(offset)

```
http://koajs.com/en
http://koajs.com/en (offset: undefined)
http://koajs.com/foo/bar/en (offset: 2)
```

#### ctx.getLocaleFromTLD(), ctx.request.getLocaleFromTLD()
Expand Down
6 changes: 3 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ module.exports = function(app, key) {

// From URL, `http://koajs.com/en`
Object.defineProperty(request, 'getLocaleFromUrl', {
value: function() {
value: function(offset) {
var segments = this.path.substring(1).split('/');
return segments.shift();
return segments[offset ? offset : 0];
}
});

Expand All @@ -89,4 +89,4 @@ module.exports = function(app, key) {
.method('getLocaleFromTLD');

return app;
};
};
19 changes: 17 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('koa-locale', function() {
});

describe('getLocaleFromUrl()', function() {
it('should get a locale from URL', function(done) {
it('should get a locale from URL with no `offset`', function(done) {
var app = koa();

locale(app);
Expand All @@ -136,6 +136,21 @@ describe('koa-locale', function() {
.expect(/en/)
.expect(200, done);
});

it('should get a locale from URL with given `offset`', function(done) {
var app = koa();

locale(app);

app.use(function*(next) {
this.body = this.getLocaleFromUrl(2);
});

request(app.listen())
.get('/foo/bar/en')
.expect(/en/)
.expect(200, done);
});
});

describe('getLocaleFromTLD()', function() {
Expand Down Expand Up @@ -168,4 +183,4 @@ describe('koa-locale', function() {
.expect(200, done);
});
});
});
});

0 comments on commit 0e8dea3

Please sign in to comment.