Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#9 API changes for File and Utils modules #10

Merged
merged 2 commits into from
Sep 8, 2015
Merged

#9 API changes for File and Utils modules #10

merged 2 commits into from
Sep 8, 2015

Conversation

tormozz48
Copy link
Contributor

Resolved #9
Needs for enb/enb-js#12

@j0tunn @blond
Please review it

* @param {Boolean} inlineSourceMap - set to true to add source map code to content
* @returns {string}
*/
render: function (inlineSourceMap) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше сделать объек опций options, с полем includeComment.

  • includeComment: 'inline' | true — добавит однострочный коментарий // ....
  • includeComment: 'block' — добавит многострочный коментарий /* ... */.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

И если вызвать file.render() без аргументов, то возвращается { contents, map } и в contents не добавляется коментарий.

@tormozz48
Copy link
Contributor Author

🆙

@@ -16,7 +17,8 @@ describe('File', function () {
it('should add a new line to the output', function () {
file.writeLine('line 1');
file.writeLine('line 2');
file.render().should.equal('line 1\nline 2\n');
file.render().contents.should.equal('line 1\nline 2\n');
expect(file.render().map).to.be.equal(null);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем проверять то, что поле с картой пустое?

@tormozz48
Copy link
Contributor Author

🆙

var content = this._content.join(os.EOL);
var sourceMap = null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется, что это не совсем ок, потому что null и undefined это не одно и тоже.

Если кто-то будет проверять через typeof, то у него не получится.

typeof res.map === 'undefined'

Я бы оставил просто var sourceMap;.

@tormozz48
Copy link
Contributor Author

и, кстати, как-то очень странно хотеть в конструкторе указывать один тип комментов, а името возможность это переопределить

Да, вопрос хороший. @blond что скажешь?

Или нужно именно иметь и склеенную строку и сам sourcemap отдельно?

Кажется, что прикольно иметь единый возвращаемый тип данных

а зачем несколько строк? У нас в конструктор передается опция comment и там inline - это значит использовать //, а block - /* */

Ошибся в jsdoc

@tormozz48
Copy link
Contributor Author

🆙

@j0tunn
Copy link
Contributor

j0tunn commented Sep 3, 2015

Есть такое предложение: не добавлять функциональности в render, пусть он как и раньше генерит склеенный контент.
Можно добавить в File два геттера: content, sourcemap.
нужен отдельно контент - file.content
нужен отдельно sourcemap - file.sourcemap
нужен склеенный кусок - file.render()

}
return content;
return {
contents: contents,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а почему, действительно, contents, а не content?

@blond
Copy link
Member

blond commented Sep 4, 2015

C Антоном согласен.

@tormozz48
Copy link
Contributor Author

🆙

@tormozz48
Copy link
Contributor Author

Сделал не геттерами в их строгом понимании а псевдогеттерами потому что:

  • Это консистентно с методом getCursor
  • ИМХО реализация геттеров и сеттеров в js оставляет желать лучшего так как по коду foo.bar
    непонятно, что это: геттер или поле bar объекта foo

@j0tunn
Copy link
Contributor

j0tunn commented Sep 4, 2015

getCursor вообще должен быть приватным.
А пользователю класса должно быть пофигу что это, по сути это и есть поле bar объекта foo, только в самом объекте оно хранится несколько в другом виде, а перед запросом преобразовывается.
С геттерами есть проблемы в другом: при тестировании их не застабаешь, и при наследовании есть проблемы с их переопределением (особенно в inherit)

@tormozz48
Copy link
Contributor Author

Ок, мне переделать или оставить как есть?

getContent: function () {
return this._content.join(os.EOL);
},

render: function () {
var content = this._content.join(os.EOL);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот здесь вполне можно заюзать getContent


file.render();
file.render({ includeComment: 'block' });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

забыл убрать

@j0tunn
Copy link
Contributor

j0tunn commented Sep 4, 2015

нужно почистить мусор от предыдущей реализации и поправить тесты: везде, где раньше использовался render как способ проверки использовать соответствующие геттеры

@tormozz48
Copy link
Contributor Author

🆙

}
return content;
return this._map ?
utils.joinContentAndSourceMap(this.getContent(), this._map, this._opts) : this.getContent();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше длинные выражения разносить так:

return this._map
    ? utils.joinCon...
    : this.getContent();

@tormozz48
Copy link
Contributor Author

🆙

@@ -164,7 +162,7 @@ describe('File', function () {

file.writeFileContent('some-file.js', middleContent);

var pos = utils.getSourceMap(file.render()).originalPositionFor({line: 1, column: 0});
var pos = getOriginalSourceMapPosition(file.getSourceMap());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

блин, андрюха, ты издеваешься? ) саму позицию-то ты зачем унес в хелпер?
Должно быть как-то так:

var pos = getOriginalPositionFor({line: 1, column: 0}, file.getSourceMap());

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет, не издеваюсь

Во всех случаях использования были именно такие аргументы которые указывают на начальную позицию.

Здесь лишь разумный компромисс между гибкостью использования хелпера и размером копипаста

@j0tunn
Copy link
Contributor

j0tunn commented Sep 4, 2015

в остальном 🆗

@tormozz48
Copy link
Contributor Author

Поправил последнее замечание
Объединил коммиты

P.S. кстати, несмотря на наличие travis.yml конфигурационного файла, что-то я не вижу
интеграции и проверки тревисом тестов. Наверное включить CI для данного репозитория.

P.S. Нужно будет выпустить обновленную версию enb-source-map

@tormozz48
Copy link
Contributor Author

Так, стоп.

Я тут попробовал использовать изменения которые мы внесли и обнаружил, что не все ок.
В enb-diverse-js мне нужно вызывать метод joinContentAndSourceMap модуля Util и передавать
в него минифицированный код и объект соурсмапа который отдает минификатор.

Но joinContentAndSourceMap сейчас принимает только экземпляры класса SourceMapGenerator, и это плохо

Нужно чтобы joinContentAndSourceMap умел работать и с экземплярами класса SourceMapGenerator и с обычными объектами sourceMap

@tormozz48
Copy link
Contributor Author

Нужно чтобы joinContentAndSourceMap умел работать и с экземплярами класса SourceMapGenerator и с обычными объектами sourceMap

Реализовал в последнем коммите.

Проверил для enb-diverse-js. Все ок.

@j0tunn
Copy link
Contributor

j0tunn commented Sep 4, 2015

я ж тебя об этом спрашивал
🆗

@tormozz48
Copy link
Contributor Author

я ж тебя об этом спрашивал

Ну лучше поздно, чем никогда.

P.S. Наверное можно мержить и выпускать версию

@blond
Copy link
Member

blond commented Sep 4, 2015

👍

@blond
Copy link
Member

blond commented Sep 4, 2015

А давайте перед выпуском обновим зависимости? А то source-map сейчас очень старый.

@j0tunn
Copy link
Contributor

j0tunn commented Sep 4, 2015

а давайте зависимости отдельным PR

@tormozz48
Copy link
Contributor Author

а давайте зависимости отдельным PR

#12

tormozz48 added a commit that referenced this pull request Sep 8, 2015
#9 API changes for File and Utils modules
@tormozz48 tormozz48 merged commit 55581dc into master Sep 8, 2015
@tormozz48 tormozz48 removed the review label Sep 8, 2015
@tormozz48 tormozz48 deleted the issue-9 branch September 8, 2015 07:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants