The document provides examples of refactoring asynchronous code in JavaScript to use promises instead of callbacks. It starts with a nested callback example to test a blog API. It then refactors the code into two versions that use the async library and make the operations more parallel. The examples are intended to illustrate how promises can make asynchronous code look more like synchronous code by removing nested callbacks. Opening the linked files provides more detailed comments explaining each example.
Ruby on Rails is an open-source web framework that is optimized for programmer happiness and productivity. It allows developers to write code more easily by favoring conventions over rigid configuration. Ruby on Rails uses conventions to make assumptions about how apps should be structured, reducing the amount of configuration code needed.
Behat is a testing framework that allows testing an entire website from the perspective of a user or tester. The document provides an overview of how to get started with Behat, including installing necessary components, writing feature files with scenarios and steps, and implementing custom steps. It also discusses best practices for writing good Behat tests and provides solutions to common problems encountered when using Behat.
The document discusses the development of Restfulness, a Ruby library for building REST APIs. It begins by outlining some irritations the author had with existing Rails controllers and API frameworks like Grape. This inspired the author to create Restfulness with a focus on simplicity, treating resources as the focus of requests, and closely following REST and HTTP principles. The summary describes the key components of Restfulness, including simple routing based on resources, separating path, query, and body parameters, and callbacks that control the flow of requests. It also mentions how Restfulness implements error handling and can be run both standalone or as part of Rails applications.
WordPress for the modern PHP developerChris Sherry
The document contains tweets from a conference session about using WordPress and version control best practices for modern PHP developers. Some key points discussed include:
- Setting up a WordPress site under version control using Git
- Managing WordPress core and plugin/theme dependencies with Composer
- Using plugins from packagist like wpackagist to install plugins via Composer
- Developing a custom plugin and publishing it to GitHub to be installed as a dependency
This document discusses crafting quality PHP applications. It emphasizes the importance of planning, writing testable code, automating testing and continuous integration/deployment. Key points covered include reducing complexity to improve testability, using different types of tests like unit and integration tests, and conducting code reviews to maintain quality. The overall message is that applying best practices around these areas leads to higher quality applications and higher confidence in releases.
The document discusses Cucumber, a tool for writing acceptance tests in a business-readable domain-specific language called Gherkin. It touches on how Cucumber supports over 28 languages by compiling Gherkin grammars into the target language. It also provides examples of tagging scenarios and features in Cucumber to enable focused testing. Finally, it recommends further reading resources for learning more about Cucumber.
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)James Titcumb
You've heard of Zend's new framework, Expressive, and you've heard it's the new hotness. In this talk, I will introduce the concepts of Expressive, how to bootstrap a simple application with the framework using best practices, and finally how to integrate a third party tool like Doctrine ORM.
The document discusses Asynchronous JavaScript and XML (Ajax) and how it can be used to retrieve data from a server without reloading the entire web page. It provides an overview of Ajax fundamentals including the XMLHttpRequest object, DOM manipulation, and different data transport options. It also recommends using a JavaScript library to simplify making Ajax requests instead of writing raw XMLHttpRequest code.
Ruby on Rails is an open-source web framework that is optimized for programmer happiness and productivity. It allows developers to write code more easily by favoring conventions over rigid configuration. Ruby on Rails uses conventions to make assumptions about how apps should be structured, reducing the amount of configuration code needed.
Behat is a testing framework that allows testing an entire website from the perspective of a user or tester. The document provides an overview of how to get started with Behat, including installing necessary components, writing feature files with scenarios and steps, and implementing custom steps. It also discusses best practices for writing good Behat tests and provides solutions to common problems encountered when using Behat.
The document discusses the development of Restfulness, a Ruby library for building REST APIs. It begins by outlining some irritations the author had with existing Rails controllers and API frameworks like Grape. This inspired the author to create Restfulness with a focus on simplicity, treating resources as the focus of requests, and closely following REST and HTTP principles. The summary describes the key components of Restfulness, including simple routing based on resources, separating path, query, and body parameters, and callbacks that control the flow of requests. It also mentions how Restfulness implements error handling and can be run both standalone or as part of Rails applications.
WordPress for the modern PHP developerChris Sherry
The document contains tweets from a conference session about using WordPress and version control best practices for modern PHP developers. Some key points discussed include:
- Setting up a WordPress site under version control using Git
- Managing WordPress core and plugin/theme dependencies with Composer
- Using plugins from packagist like wpackagist to install plugins via Composer
- Developing a custom plugin and publishing it to GitHub to be installed as a dependency
This document discusses crafting quality PHP applications. It emphasizes the importance of planning, writing testable code, automating testing and continuous integration/deployment. Key points covered include reducing complexity to improve testability, using different types of tests like unit and integration tests, and conducting code reviews to maintain quality. The overall message is that applying best practices around these areas leads to higher quality applications and higher confidence in releases.
The document discusses Cucumber, a tool for writing acceptance tests in a business-readable domain-specific language called Gherkin. It touches on how Cucumber supports over 28 languages by compiling Gherkin grammars into the target language. It also provides examples of tagging scenarios and features in Cucumber to enable focused testing. Finally, it recommends further reading resources for learning more about Cucumber.
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)James Titcumb
You've heard of Zend's new framework, Expressive, and you've heard it's the new hotness. In this talk, I will introduce the concepts of Expressive, how to bootstrap a simple application with the framework using best practices, and finally how to integrate a third party tool like Doctrine ORM.
The document discusses Asynchronous JavaScript and XML (Ajax) and how it can be used to retrieve data from a server without reloading the entire web page. It provides an overview of Ajax fundamentals including the XMLHttpRequest object, DOM manipulation, and different data transport options. It also recommends using a JavaScript library to simplify making Ajax requests instead of writing raw XMLHttpRequest code.
Performance optimization is a crucial aspect of building ‘snappy’ client-side applications and something which all developers using jQuery should bear in mind. In this talk, we're going to take a look at some of the best practices, tips and tricks for improving the performance of your jQuery code in 2011 with some quick wins and a few new surprises along the way.
Deploying a Location-Aware Ember ApplicationBen Limmer
Learn how to deploy a location aware EmberJS application to heroku. This presentation explains how to use ember-cli-deploy along with heroku redis and s3 to create an application that dynamically changes the internationalization translation based on what country you're visiting the site from. Also uses ember-cli-server-variables, ember-i18n, node-ember-cli-deploy-redis, cheeriojs, and ember-cli.
This prototype works, but it's not pretty, and now it's in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it's imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we'll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
This document summarizes Nicholas C. Zakas's presentation on maintainable JavaScript. The presentation discusses why maintainability is important, as most time is spent maintaining code. It defines maintainable code as code that works for five years without major changes and is intuitive, understandable, adaptable, extendable, debuggable and testable. The presentation covers code style guidelines, programming practices, code organization techniques and automation tools to help write maintainable JavaScript.
Why and when you need end-to-end tests, a spooky story with a 15 years software beast, and how to develop concise, maintainable functional tests using Groovy, Spock and Geb.
This prototype works, but it’s not pretty, and now it’s in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it’s imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we’ll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
This prototype works, but it's not pretty, and now it's in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it's imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we'll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
Crafting Quality PHP Applications (PHP Joburg Oct 2019)James Titcumb
This prototype works, but it’s not pretty, and now it’s in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it’s imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we’ll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
The document discusses Step Objects, which are presented as an alternative to Page Objects and as a way to structure behavioral tests. Step Objects sit between Page Objects and behavior/test definitions. They are introduced as a layer that allows defining steps to act and verify without being tied to specific pages. The rest of the document covers example step definitions, using generic steps, handling data passing between steps, and principles for step organization.
This document provides summaries of key points about the jQuery and Prototype JavaScript libraries:
1. jQuery is an open-source JavaScript library that simplifies HTML document traversal, event handling, animation, and Ajax interactions. It has a lightweight footprint and is cross-browser compatible.
2. Both jQuery and Prototype are available under MIT and GPL licenses, allowing developers to choose the license that best suits their projects. jQuery is maintained by a core team and has additional community support.
3. The document then provides examples of common jQuery functions and selectors for manipulating the DOM, handling events, animating elements, and making Ajax requests.
Outside-in Development with Cucumber and RspecJoseph Wilk
Talk given by Joseph Wilk at Scotland on Rails 2009. Examines how Cucumber and Rspec fit together in the testing workflow, how and why Cucumber is useful and how it works. Walks through a simple example based on renting DVDs showing how to use Cucumber and some of the best practices. Looks at how Webrat can drive Selenium to in-turn drive Cucumber features through the browser.
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)James Titcumb
Security is an enormous topic, and it’s really, really complicated. If you’re not careful, you’ll find yourself vulnerable to any number of attacks which you definitely don’t want to be on the receiving end of. This talk will give you just a taster of the vast array of things there is to know about security in modern web applications, such as writing secure PHP web applications and securing a Linux server. Whether you are writing anything beyond a basic brochure website, or even developing a complicated business web application, this talk will give you insights to some of the things you need to be aware of.
This document contains Simon Willison's heresies about Django. Some of the heresies discussed include that the {% if %} tags in Django templates suck, that silencing template errors is a bad idea, and that settings.py causes problems. Alternatives proposed include using a smarter {% if %} tag snippet, not silencing errors, and allowing per-application settings instead of one global settings file. The document also advocates for improving testing and documentation in the Django community.
Best practices for crafting high quality PHP apps (php[world] 2019)James Titcumb
The Best Practices for Crafting Quality PHP Applications workshop is an interactive exploration into some conventions, processes, and habits that help make better quality software. Whilst there is no single silver bullet, we will spend time discussing, supported by some practical exercises, what improvements we can make. We’ll focus on three core areas; planning, development, and testing; using a variety of practical explorations, group discussion and showing you discoveries from my own experience.
The document provides an introduction to Ruby on Rails for beginners. It covers various Ruby and Rails concepts like objects, classes, MVC framework, Active Record, routing and controllers. It then demonstrates how to build a basic Rails application with models, views and controllers to manage products using CRUD actions and RESTful routing.
Turn your spaghetti code into ravioli with JavaScript modulesjerryorr
JavaScript is the language that powers the interactive web of the future. But as our web applications become larger and more complex, we begin to strain the old paradigm of throwing a bunch of JavaScript functions into a few files. Complex dependencies, tight coupling, and global state can turn our code into a huge plate of spaghetti. Though browsers do not natively support JavaScript modules, there are many tools that can help us to write clean, modular JavaScript.
In this session, we will explore the benefits of writing modular JavaScript. We will also take a deep dive into specific JavaScript module systems, such as Browserify, RequireJS, and the module standards that are coming in ES6.
Building a Single Page Application using Ember.js ... for fun and profitBen Limmer
Denver Startup Week 2015 Talk. The talk is split into two sections: conceptual reasons you might choose a framework like EmberJS where convention over configuration is preferred, and a live coding demo where we build a simple EmberJS application for our up-and-coming business, Bluth's Banana Stand.
What is the purpose of BDD and how it fits into the Agile development? If you ever wondered what are the benefits of BDD or why should you care about tools like Behat or PhpSpec, this talk will try to guide you through the reasoning and goals of modern Agile practices and tools in PHP.
Performance optimization is a crucial aspect of building ‘snappy’ client-side applications and something which all developers using jQuery should bear in mind. In this talk, we're going to take a look at some of the best practices, tips and tricks for improving the performance of your jQuery code in 2011 with some quick wins and a few new surprises along the way.
Deploying a Location-Aware Ember ApplicationBen Limmer
Learn how to deploy a location aware EmberJS application to heroku. This presentation explains how to use ember-cli-deploy along with heroku redis and s3 to create an application that dynamically changes the internationalization translation based on what country you're visiting the site from. Also uses ember-cli-server-variables, ember-i18n, node-ember-cli-deploy-redis, cheeriojs, and ember-cli.
This prototype works, but it's not pretty, and now it's in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it's imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we'll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
This document summarizes Nicholas C. Zakas's presentation on maintainable JavaScript. The presentation discusses why maintainability is important, as most time is spent maintaining code. It defines maintainable code as code that works for five years without major changes and is intuitive, understandable, adaptable, extendable, debuggable and testable. The presentation covers code style guidelines, programming practices, code organization techniques and automation tools to help write maintainable JavaScript.
Why and when you need end-to-end tests, a spooky story with a 15 years software beast, and how to develop concise, maintainable functional tests using Groovy, Spock and Geb.
This prototype works, but it’s not pretty, and now it’s in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it’s imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we’ll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
This prototype works, but it's not pretty, and now it's in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it's imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we'll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
Crafting Quality PHP Applications (PHP Joburg Oct 2019)James Titcumb
This prototype works, but it’s not pretty, and now it’s in production. That legacy application really needs some TLC. Where do we start? When creating long lived applications, it’s imperative to focus on good practices. The solution is to improve the whole development life cycle; from planning, better coding and testing, to automation, peer review and more. In this talk, we’ll take a quick look into each of these areas, looking at how we can make positive, actionable change in our workflow.
The document discusses Step Objects, which are presented as an alternative to Page Objects and as a way to structure behavioral tests. Step Objects sit between Page Objects and behavior/test definitions. They are introduced as a layer that allows defining steps to act and verify without being tied to specific pages. The rest of the document covers example step definitions, using generic steps, handling data passing between steps, and principles for step organization.
This document provides summaries of key points about the jQuery and Prototype JavaScript libraries:
1. jQuery is an open-source JavaScript library that simplifies HTML document traversal, event handling, animation, and Ajax interactions. It has a lightweight footprint and is cross-browser compatible.
2. Both jQuery and Prototype are available under MIT and GPL licenses, allowing developers to choose the license that best suits their projects. jQuery is maintained by a core team and has additional community support.
3. The document then provides examples of common jQuery functions and selectors for manipulating the DOM, handling events, animating elements, and making Ajax requests.
Outside-in Development with Cucumber and RspecJoseph Wilk
Talk given by Joseph Wilk at Scotland on Rails 2009. Examines how Cucumber and Rspec fit together in the testing workflow, how and why Cucumber is useful and how it works. Walks through a simple example based on renting DVDs showing how to use Cucumber and some of the best practices. Looks at how Webrat can drive Selenium to in-turn drive Cucumber features through the browser.
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)James Titcumb
Security is an enormous topic, and it’s really, really complicated. If you’re not careful, you’ll find yourself vulnerable to any number of attacks which you definitely don’t want to be on the receiving end of. This talk will give you just a taster of the vast array of things there is to know about security in modern web applications, such as writing secure PHP web applications and securing a Linux server. Whether you are writing anything beyond a basic brochure website, or even developing a complicated business web application, this talk will give you insights to some of the things you need to be aware of.
This document contains Simon Willison's heresies about Django. Some of the heresies discussed include that the {% if %} tags in Django templates suck, that silencing template errors is a bad idea, and that settings.py causes problems. Alternatives proposed include using a smarter {% if %} tag snippet, not silencing errors, and allowing per-application settings instead of one global settings file. The document also advocates for improving testing and documentation in the Django community.
Best practices for crafting high quality PHP apps (php[world] 2019)James Titcumb
The Best Practices for Crafting Quality PHP Applications workshop is an interactive exploration into some conventions, processes, and habits that help make better quality software. Whilst there is no single silver bullet, we will spend time discussing, supported by some practical exercises, what improvements we can make. We’ll focus on three core areas; planning, development, and testing; using a variety of practical explorations, group discussion and showing you discoveries from my own experience.
The document provides an introduction to Ruby on Rails for beginners. It covers various Ruby and Rails concepts like objects, classes, MVC framework, Active Record, routing and controllers. It then demonstrates how to build a basic Rails application with models, views and controllers to manage products using CRUD actions and RESTful routing.
Turn your spaghetti code into ravioli with JavaScript modulesjerryorr
JavaScript is the language that powers the interactive web of the future. But as our web applications become larger and more complex, we begin to strain the old paradigm of throwing a bunch of JavaScript functions into a few files. Complex dependencies, tight coupling, and global state can turn our code into a huge plate of spaghetti. Though browsers do not natively support JavaScript modules, there are many tools that can help us to write clean, modular JavaScript.
In this session, we will explore the benefits of writing modular JavaScript. We will also take a deep dive into specific JavaScript module systems, such as Browserify, RequireJS, and the module standards that are coming in ES6.
Building a Single Page Application using Ember.js ... for fun and profitBen Limmer
Denver Startup Week 2015 Talk. The talk is split into two sections: conceptual reasons you might choose a framework like EmberJS where convention over configuration is preferred, and a live coding demo where we build a simple EmberJS application for our up-and-coming business, Bluth's Banana Stand.
What is the purpose of BDD and how it fits into the Agile development? If you ever wondered what are the benefits of BDD or why should you care about tools like Behat or PhpSpec, this talk will try to guide you through the reasoning and goals of modern Agile practices and tools in PHP.
This document discusses Java 8 features including lambda expressions, default methods, and the new date/time API. It provides examples of using lambda expressions to iterate through collections and streams, including filtering streams. It also covers the new date/time classes like LocalDate, LocalTime, ZonedDateTime and others that provide improved date/time handling over Java 8.
Страница должна загружаться быстрее чем 1 секунда; количество серверных запросов должно быть сведено к минимуму; CSS и JS файлы должны быть сжаты и не превышать 50 килобайт…” Это лишь малая часть технических решений и рекомендаций, которыми нас снабжает индустрия в погоне за производительностью. Но во всем этом есть одна проблема – пользователям нет никакого дела до килобайтов, миллисекунд и количества запросов. Производительность – это не математика. Производительность — это восприятие. Именно восприятие может создает впечатление медлительности сайта с малым количеством серверных запросов, в то время как сайт, возвращающий результаты поиска в течение секунд, может восприниматься как достаточно быстрый для пользователя. И именно восприятие пользователя является единственным мерилом производительности вашего сайта.
В докладе будут рассмотрены психологические и технические теории, приемы и примеры, позволяющие управлять восприятием пользователя
Полная версия презентации по ссылке: http://goo.gl/1iBNNO
... ничего такого не произойдет :) Их сложно начать писать, нужно мотивировать команду, а самое главное — непонятно, зачем? Ведь можно открыть браузер и в пару кликов проверить все ли в порядке с приложением.
Доклад о том, как много мы теряем, если не пишем тесты. Я покажу, с чего начать, какие инструменты и методики можно использовать. Поделюсь собственным опытом разработки JavaScript тестов. Постараюсь показать, как тесты смогут сделать ваш проект лучше.
Migrate your React.js application from (m)Observable to ReduxFDConf
Вся презентация по ссылке: goo.gl/FySndO
0) Intro about our Content Browser project architecture.
1) Problem with current state in Fluxx world.
2) Observable pattern like temporal decision.
3) Complexity and Pay off.
4) Redux is not panacea but it is the best what we have.
6) Migration tricks or how to reduce the pain.
7) Conclusion.
The document discusses test-driven development (TDD) and how it provides consistent answers to questions about how to get started with testing code. It demonstrates TDD by walking through an example of writing tests and code to create a blog post. Key points made include: write tests before code; write one acceptance test and unit tests at a time; use test doubles in unit tests; and iterate between writing a test, making it pass by writing minimal code, then refactoring as needed. The process involves two "red-green-refactor" loops between acceptance and unit test levels.
This document discusses JavaScript and its popularity. JavaScript is one of the core languages used to build dynamic web applications. It has enabled features like Google Maps that provide dynamic and interactive experiences to users. JavaScript's cross-platform compatibility allows developers to write code once that runs on different operating systems. It is also used for server-side programming with Node.js. Popular frameworks like React and Angular are built with JavaScript. Overall, JavaScript has become very popular due to its ability to create rich and engaging user interfaces across different platforms and devices.
The document discusses using promises to write asynchronous code in a synchronous style. It provides examples of testing a blog API using callbacks, async/await, and promises. With callbacks, the code is nested and difficult to follow. Using async/await and promises helps linearize the code and make the asynchronous logic clearer and easier to read. Promises transform asynchronous code into a series of synchronous-looking steps chained together with .then() calls. This improves readability and maintainability compared to deeply nested callbacks.
The document discusses best practices for testing Rails controllers. It recommends writing declarative tests that focus on authentication, authorization, resource presence, and responses. Shared examples should be used to DRY up tests for these "small details". Tests for "big actions" like fetching a resource can be simple. Business logic belongs in models, not controllers. ActiveModel makes it easy to extract logic out of controllers and into reusable classes. Overall, the goal is to keep controllers simple and focused on their main responsibilities by writing declarative, well-factored tests.
The document contains the first 30 questions from a list of top 150 JavaScript interview questions. It covers topics like the differences between Java and JavaScript, data types in JavaScript, how to create arrays and objects, variable declaration keywords like var, let and const, and other fundamental concepts like functions, closures, promises and more.
- The document discusses AngularJS and single page applications. It provides an introduction and overview of key AngularJS concepts including modules, controllers, views, services, dependency injection, and filters.
- Code samples and demos are referenced to illustrate concepts in more depth. Challenges with SEO and the benefits of TypeScript for adding type safety to JavaScript are also mentioned.
JavaScript can change HTML content, attributes, styles, and validate data. It can be placed in the <body> and <head> sections between <script> tags. Functions and events allow JavaScript code to run when events occur. JavaScript can output to alerts, the document, elements, and the console. It uses data types like numbers, strings, Booleans, arrays, and objects. Conditionals like if/else and switch statements allow different code blocks to run based on conditions. Loops like for, for/in, while, and do/while repeat code.
Build a game with javascript (may 21 atlanta)Thinkful
This document provides an overview of building a game with JavaScript. It discusses setting up the project, refresher lessons on HTML/CSS, breaking the game into JavaScript functions, and getting user input. The roadmap outlines generating a random number on page load, accepting user guesses, providing feedback, and allowing new games. Homework involves adding more specific feedback, counting guesses, outputting guesses to a list, and a new game button. Learning support includes 1-on-1 mentoring from experienced developers and round-the-clock support. Thinkful reports job placements within months in titles like web developer.
Plugin Development @ WordCamp Norway 2014Barry Kooij
This document summarizes a presentation on plugin development for WordPress. The presentation covers topics like plugin architecture, coding standards, documentation, testing, security, internationalization, and more. It emphasizes best practices for WordPress plugin development like using the WordPress API, hooks and filters, object-oriented programming, documentation, testing, and security practices like sanitizing data.
This document provides an introduction to JavaScript. It discusses the basics of how the web works with clients and servers, gives a brief history of JavaScript, and covers key JavaScript concepts like variables, data types, functions, and parameters. The format for the session is outlined, which includes reviewing these concepts, practicing with challenges, and discussing next steps for continuing to learn.
The document discusses the new JSON REST API for WordPress, which provides a modern REST API for WordPress sites using JSON instead of the outdated XML-RPC format. It allows users to create, read, update and delete WordPress content like posts, pages, users and media through HTTP requests. The API can be accessed through plugins or by making requests directly to the /wp-json/ endpoints. It also supports features like authentication, pagination and filtering to build powerful applications that interact with WordPress content and data.
This document discusses various techniques for building APIs with Rails including:
- Using Rails routing and controllers to define API endpoints and resources
- Content negotiation to support different response formats like JSON and XML
- Authentication methods like HTTP basic authentication and token-based authentication
- Versioning API resources to maintain backwards compatibility
- Testing APIs to validate status codes, response formats, authentication, and more
Don't RTFM, WTFM - Open Source Documentation - German Perl Workshop 2010singingfish
The document discusses improving documentation for Perl modules like Moose and Catalyst by focusing on providing working code examples and minimizing extraneous information. It advocates for an incremental, "git-based" approach to introducing concepts one by one and advertising examples. Key points made include assuming readers have minimal knowledge, reducing cognitive load, and crowdsourcing documentation improvements through a standard Pod format. Contributors are tasked with improving specific documentation areas by these principles.
Node.js is an event-driven I/O platform for JavaScript that allows non-blocking, asynchronous code for building scalable network applications. It uses an event loop model that handles concurrent connections efficiently by doing useful work on the CPU when waiting for I/O operations to complete. Node.js comes with a package manager (NPM) and a rich ecosystem of modules. It is well-suited for real-time applications due to its asynchronous and non-blocking nature which allows for high throughput and scalability.
This document provides an introduction to JavaScript, covering key concepts like variables, data types, functions, and how the web works. It begins with introductions from the instructor and mentor. It then discusses programming fundamentals like defining problems, finding solutions, and implementing them in code. The document explains that JavaScript is used for both front-end and back-end development. It covers JavaScript variables, strings, numbers, Booleans, and basic functions. It provides examples and challenges for readers to practice the concepts. In the end, it discusses continuing education options through 1-on-1 mentorship.
Why you should be using the shiny new C# 6.0 features now!Eric Phan
C# 6.0 will change the way you write C#. There are many language features that are so much more efficient you’ll wonder why they weren’t there since the beginning.
Intro to JavaScript - Thinkful LA, June 2017Thinkful
This document provides an introduction to JavaScript for beginners. It covers basic JavaScript concepts like variables, data types, functions, and objects. It also explains how the web works at a high level with clients making requests to servers. The document is meant to give attendees an overview of key JavaScript concepts to practice during a workshop on getting started with JavaScript.
Testing swagger contracts without contract based testingАлексей Стягайло
Contract based testing is one of the main microservices testing solutions, but it has several restrictions: need deep knowledge about microservice, used frameworks and program language. In my talk, I will show how our team checking differences between Swagger/OpenAPI specs, generate json schemas from swagger json files and comparing json schema and real response.
Journey To The Front End World - Part3 - The MachineIrfan Maulana
This document is a summary of part 3 of a journey to the front end world. It provides an introduction to JavaScript, including what it is, its uses, data types, operators, conditional statements, loops, functions, and scope. It also discusses ECMAScript, the DOM tree, developer tools, and code conventions. Hands-on examples are provided to add CRUD interactions with local storage. References for further learning are included, and contact information is provided for the author.
Антон Киршанов - «Квант изменения. Реактивные реакции на React.FDConf
Современные интерактивные приложения в вебе требуют особого внимания к работе с непрерывно изменяющимися, динамическими данными. RxJS – библиотека, построенная на паттерне Observable/Observer, выражает последовательность изменений в состоянии приложения через внешние потоки данных и предоставляет широкий набор средств для создания, фильтрации, комбинирования таких потоков удобным для разработчика способом. Для наглядной демонстрации преимуществ такого подхода в докладе будут рассмотрены некоторые примеры с использованием библиотеки React, они помогут осознать основные принципы связывания потоков данных и представления, а также увидеть гибкость, компактность и практическую ценность предлагаемого библиотекой RxJS метода.
Насколько сложно создать виртуальный тур и добавить на сайт? Я расскажу как сделать это за 5 минут, мы добавим его на веб страницу, откроем в мобильном браузере и запустим в очках виртуальной реальности. Разберёмся как всё устроено, рассмотрим библиотеку THREE.js и технологию WebGL.
Илья Климов - Reason: маргиналы против хайпаFDConf
ClojureScript, Elm, PureScript, CoffeeScript, Dart, Kotlin. Этот список языков, так или иначе транспилирующихся в JavaScript можно продолжать бесконечно. В своем докладе я расскажу о Reason - еще одной попытке, в этот раз от Facebook?влиться в это движение. Или все же нет? В докладе я сфокусируюсь не столько на том, как Reason крут, сколько на том, какую ценность он составляет для JavaScript разрабочика, кому он нужен и свой реальный опыт практического использования.
Максим Щепелин - Доставляя веб-контент в игруFDConf
За 7 лет развития World of Tanks, сложность игрового клиента и сервера значительно выросла. Если сервер можно разделить на сервисы, то клиент остается огромным монолитом в миллионы строк кода на ActionScript, C++ и Python.
Мы решили проблему сложности, встаиванием браузера в игровой клиент и заменив частично на нативные интерфесы на веб-контент. О преимуществах и недостатках этого подхода я расскажу в своём докладе.
Radoslav Stankov - Handling GraphQL with React and ApolloFDConf
For almost an year I'm was working on GraphQL projects. In the talk, I'm going to share my experiences working with GraphQL with React and Apollo. I would cover the following talk points:
what is GraphQL
why are people so excited about GraphQL
how to use GraphQL with React
how to solve common problems with GraphQL
Виктор Русакович - Выборы, выборы, все фреймворки… приторныFDConf
Пять лет назад присоединился к команде разработки проекта, над которым до сих пор идёт работа. За это время приложения, создаваемые в рамках проекта, использовали разные фреймворки - от jQuery до React, от Backbone до Angular.
Как мы выбираем фреймворк для нашего следующего приложения? Какой фреймворк самый лучший? Как выбрать фреймворк и через год разочароваться в своём выборе? Короткая история о выборах в одном длинном проекте.
Slobodan Stojanovic - 8 1/2 things about serverless FDConf
What is serverless? How does it work? Can you explain it with something as simple as Lego bricks?
This talk will answer that and at least five and a half more questions. It’s main goal is to explain serverless architecture, show you why it’s important, and finally, show you why it works great with Node.js and how to use it.
PWA – это сейчас хайп тренд. Google и Microsoft говорят про них на своих конференциях. Twitter и Uber переписывают на них свои мобильные версии веб-приложений. И вот, работая над своим проектом, я решил сделать его Progressive и протестировать на реальных пользователях в production. В этом докладе я расскажу как я это делал и какую пользу это принесло проекту.
Вся презентация по ссылке: goo.gl/WuwMZL
Если ваш проект перевалил за миллион строк кода, а количество разработчиков за десяток - то вам уже пришлось столкнутся с проблемами JS и его масштабируемости. В данном докладе будет рассказано о том, как решить эти проблемы, как начать использовать Dart, послойно встраивая его в устаревший код и как растить команду с помощью типизированного языка.
This document discusses scalable application architecture. It covers topics like dynamic requirements, using a scalable communication layer with various package formats, handling multiple state mutation sources, building scalable teams, and lazy loading. It provides examples of component architecture using Angular, services, state management with ngrx/redux, immutability with ImmutableJS, and asynchronous logic with RxJS. The goal is to build modular, extensible applications that can handle complex requirements through separation of concerns and well-designed architecture.
JavaScript является одни из самых популярных языков программирования. На сегодняшний день его можно использовать не только в браузере, но и на сервере, в системах управления баз данных, программировать микроконтроллеры, писать десктопные и мобильные приложения. В данном докладе я расскажу о современном JavaScript и его областях применения (Mongo, CouchDB, Node, Meteor, tessel, PhoneGap, ReactNative и так далее), а также загляну немного в будущее и покажу вам куда он движется (ES2015, ES2016 ... ESxxxx, WebAssembly). И много-много всего интересного с демками)
CSSO – инструмент для минификации CSS, который недавно вернулся к активной разработке. Зачем?
Дело в том, что минификация CSS – задача сложная. Сейчас нет идеального минификатора, и чтобы эффективным был и делал все правильно. Ведь нужно учитывать не только особенности CSS, который постоянно меняется, но и уровень его поддержки браузерами, их баги, префиксы, хаки и т.д. Все это требует решения ряда непростых задач. Поговорим об этом, а так же принципах работы CSS-минификаторов, новых идеях и развитии CSSO.
Подробнее: http://www.slideshare.net/basisjs/csso-compress-css-english-version
Redux - негласный победитель Flux соревнований, одна из трендовых библиотек 2015 года. Слишком "сырой" для продакшена? Нет, мы так не думаем! Используя силу функционального подхода и модель Event Sourcing'a, Redux позволяет гибко управлять состоянием вашего приложения. В докладе мы расскажем про то, как мы, используя связку Redux+React, переписали с нуля front-end одного из наших продуктов (Лидсканер | leadscanner.ru). Рассмотрим реальные плюсы и минусы данного стека, в частности: работу с side-effects, повторное использование компонентов, тестируемость.
Структура:
Про нас.
Какие перед нами стояли вызовы.
Многоуровневая архитектура.
Обзор Flux архитектуры.
Redux - Predictable state container for JavaScript apps.
React как view layer.
Повторное использование компонентов.
Dumb and Smart components.
Feature Folders.
Работа с side effects.
Обзор подходов организации actionCreators.
Middlewares.
Redux-saga.
Минусы данного стека.
Каждый день появляется по новому JavaScript фрeймворку или новой технологии. И каждый день мы задаемся вопросом, как за всем этим успеть? Константин даст Вам серебряную пулю. Вы будете знать, как быстро разобраться в React, PostCss, RxJS, Redux, CycleJs, Angular и даже в неизвестном супер фреймворке. Увидим, что стоит за трендами технологий 2016.
Подробнее: https://mavrin.github.io/pres-be-first/#1
"Service Worker: Let Your Web App Feel Like a Native "FDConf
Service workers allow web applications to work offline by intercepting network requests, caching responses, and serving cached resources when there is no network connection. They also handle background synchronization and push notifications. Key capabilities include making apps available offline, controlling the cache and network requests, and subscribing to push notifications. Service workers operate separately from the main thread of the page, intercepting and modifying fetch events to return cached responses when available.
"В последнее время тема пиринговых технологий становится очень популярной. Уже не первый день работают такие проекты как криптовалюта Bitcoin, микроблоги Twister и мессенджер Tox. Теперь дошло дело и до децентрализованного веба.
Будет рассказано про общую схему работы сети, о работе с криптографией на JavaScript, о создании приложений на JavaScript без использования центральных серверов."
«I knew there had to be a better way to build mobile app»FDConf
I knew there had to be a better way to build mobile apps.
The time has never been better to learn mobile application development. For many app ideas, you don’t even need any prior native development knowledge. You can get started today with knowledge of HTML, CSS and JavaScript. Unlike native mobile development, mobile applications using web technologies can support many mobile platforms.
So during this session will gain experience how to start from very basics and build mobile apps with zero knowledge. Alius will share his own experience on building hybryd applications based on PhoneGap also he promised to explain why he suddenly changed his own opinion about native apps and switched back to Xamarin.
«Как перестать отлаживать асинхронные вызовы и начать жить»FDConf
Асинхронность в Javascript больше не страшна. Классические триллеры вроде
«Callback Hell» и «Pyramid of Doom» потеряли свою актуальность настолько,что даже Java-программисты перестали пугать ими невинных джуниоров.
Всё благодаря паттернам и библиотекам. Streams, Promises, Async-Await и другие изменили наш код. Теперь он прекрасен.
Пока ещё вымысел? Поговорим о том, как сделать эту картину реальностью. Об основных практиках асинхронного программирования.
Принципах их работы,отличиях и сценариях использования.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Webinar: Designing a schema for a Data WarehouseFederico Razzoli
Are you new to data warehouses (DWH)? Do you need to check whether your data warehouse follows the best practices for a good design? In both cases, this webinar is for you.
A data warehouse is a central relational database that contains all measurements about a business or an organisation. This data comes from a variety of heterogeneous data sources, which includes databases of any type that back the applications used by the company, data files exported by some applications, or APIs provided by internal or external services.
But designing a data warehouse correctly is a hard task, which requires gathering information about the business processes that need to be analysed in the first place. These processes must be translated into so-called star schemas, which means, denormalised databases where each table represents a dimension or facts.
We will discuss these topics:
- How to gather information about a business;
- Understanding dictionaries and how to identify business entities;
- Dimensions and facts;
- Setting a table granularity;
- Types of facts;
- Types of dimensions;
- Snowflakes and how to avoid them;
- Expanding existing dimensions and facts.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxSitimaJohn
Ocean Lotus cyber threat actors represent a sophisticated, persistent, and politically motivated group that poses a significant risk to organizations and individuals in the Southeast Asian region. Their continuous evolution and adaptability underscore the need for robust cybersecurity measures and international cooperation to identify and mitigate the threats posed by such advanced persistent threat groups.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Testing web APIs
1. jakobm.com
@jakobmattsson
I’m a coder first and foremost. I also help
companies recruit coders, train coders and
architect software. Sometimes I do technical
due diligence and speak at conferences.
!
Want more? Read my story or blog.
7. Example - Testing a blog API
• Create a blog
• Create two blog entries
• Create two users
• Create a lotal of three comments from
those users, on the two posts
• Request the stats for the blog and
check if the given number of entries
and comments are correct
13. Why is that
a good idea?
• Loosen up the coupling
• Superior error handling
• Simplified async
14. Why is that
a good idea?
• Loosen up the coupling
• Superior error handling
• Simplified async
But in particular, it abstracts away the temporal
dependencies in your program (or in this case, test)
15. That’s enough 101
(even though people barely talk about
the last - and most important - idea)
17. Promises are not new
http://github.com/kriskowal/q
http://www.html5rocks.com/en/tutorials/es6/promises
http://domenic.me/2012/10/14/youre-missing-the-point-of-promises
http://www.promisejs.org
https://github.com/bellbind/using-promise-q
https://github.com/tildeio/rsvp.js
https://github.com/cujojs/when
26. getJSON('story.json').then(function(story) {
addHtmlToPage(story.heading);
!
// Map our array of chapter urls to
// an array of chapter json promises.
// This makes sture they all download parallel.
return story.chapterUrls.map(getJSON)
.reduce(function(sequence, chapterPromise) {
// Use reduce to chain the promises together,
// adding content to the page for each chapter
return sequence.then(function() {
// Wait for everything in the sequence so far,
// then wait for this chapter to arrive.
return chapterPromise;
}).then(function(chapter) {
addHtmlToPage(chapter.html);
});
}, Promise.resolve());
}).then(function() {
addTextToPage('All done');
}).catch(function(err) {
// catch any error that happened along the way
addTextToPage("Argh, broken: " + err.message);
}).then(function() {
document.querySelector('.spinner').style.display = 'none';
});
As announced
for ES6
36. 1 Promises out: Always return promises -
not callback
2 Promises in: Functions should accept
promises as well as regular values
3 Promises between: Augment promises as
you augment regular objects
Three requirements
38. Example - Testing a blog API
• Create a blog
• Create two blog entries
• Create some users
• Create some comments from those
users, on the two posts
• Request the stats for the blog and
check if the given number of entries
and comments are correct
39. post('/blogs', {
name: 'My blog'
}, function(err, blog) {
! post(concatUrl('blogs', blog.id, 'entries'), {
title: 'my first post’,
body: 'Here is the text of my first post'
}, function(err, entry1) {
! post(concatUrl('blogs', blog.id, 'entries'), {
title: 'my second post’,
body: 'I do not know what to write any more...'
}, function(err, entry2) {
! post('/user', {
name: 'john doe’
}, function(err, visitor1) {
! post('/user', {
name: 'jane doe'
}, function(err, visitor2) {
! post('/comments', {
userId: visitor1.id,
entryId: entry1.id,
text: "well written dude"
}, function(err, comment1) {
! post('/comments', {
userId: visitor2.id,
entryId: entry1.id,
text: "like it!"
}, function(err, comment2) {
! post('/comments', {
userId: visitor2.id,
entryId: entry2.id,
text: "nah, crap"
}, function(err, comment3) {
! get(concatUrl('blogs', blog.id), function(err, blogInfo) {
assertEquals(blogInfo, {
name: 'My blog',
numberOfEntries: 2,
numberOfComments: 3
});
});
});
});
});
});
});
});
});
});
https://
github.com/
jakobmattsson/
z-presentation/
blob/master/
promises-in-out/
1-naive.js
1
Note: without narration, this slide lacks a lot of
context. Open the file above and read the
commented version for the full story.
40. post('/blogs', {
name: 'My blog'
}, function(err, blog) {
! var entryData = [{
title: 'my first post',
body: 'Here is the text of my first post'
}, {
title: 'my second post',
body: 'I do not know what to write any more...'
}]
! async.forEach(entryData, function(entry, callback), {
post(concatUrl('blogs', blog.id, 'entries'), entry, callback);
}, function(err, entries) {
! var usernames = ['john doe', 'jane doe'];
! async.forEach(usernames, function(user, callback) {
post('/user', { name: user }, callback);
}, function(err, visitors) {
! var commentsData = [{
userId: visitor[0].id,
entryId: entries[0].id,
text: "well written dude"
}, {
userId: visitor[1].id,
entryId: entries[0].id,
text: "like it!"
}, {
userId: visitor[1].id,
entryId: entries[1].id,
text: "nah, crap"
}];
! async.forEach(commentsData, function(comment, callback) {
post('/comments', comment, callback);
}, function(err, comments) {
! get(concatUrl('blogs', blog.id), function(err, blogInfo) {
! assertEquals(blogInfo, {
name: 'My blog',
numberOfEntries: 2,
numberOfComments: 3
});
});
});
});
});
});
https://
github.com/
jakobmattsson/
z-presentation/
blob/master/
promises-in-out/
2-async.js
2
Note: without narration, this slide lacks a lot of
context. Open the file above and read the
commented version for the full story.
41. https://
github.com/
jakobmattsson/
z-presentation/
blob/master/
promises-in-out/
3-async-more-parallel.js
3
Note: without narration, this slide lacks a lot of
context. Open the file above and read the
commented version for the full story.
post('/blogs', {
name: 'My blog'
}, function(err, blog) {
! async.parallel([
function(callback) {
var entryData = [{
title: 'my first post',
body: 'Here is the text of my first post'
}, {
title: 'my second post',
body: 'I do not know what to write any more...'
}];
async.forEach(entryData, function(entry, callback), {
post(concatUrl('blogs', blog.id, 'entries'), entry, callback);
}, callback);
},
function(callback) {
var usernames = ['john doe', 'jane doe’];
async.forEach(usernames, function(user, callback) {
post('/user', { name: user }, callback);
}, callback);
}
], function(err, results) {
! var entries = results[0];
var visitors = results[1];
! var commentsData = [{
userId: visitors[0].id,
entryId: entries[0].id,
text: "well written dude"
}, {
userId: visitors[1].id,
entryId: entries[0].id,
text: "like it!"
}, {
userId: visitors[1].id,
entryId: entries[1].id,
text: "nah, crap"
}];
! async.forEach(commentsData, function(comment, callback) {
post('/comments', comment, callback);
}, function(err, comments) {
! get(concatUrl('blogs', blog.id), function(err, blogInfo) {
assertEquals(blogInfo, {
name: 'My blog',
numberOfEntries: 2,
numberOfComments: 3
});
});
});
});
});
42. post('/blogs', {
name: 'My blog'
}).then(function(blog) {
! var visitor1 = post('/user', {
name: 'john doe'
});
! var visitor2 = post('/user', {
name: 'jane doe'
});
! var entry1 = post(concatUrl('blogs', blog.id, 'entries'), {
title: 'my first post',
body: 'Here is the text of my first post'
});
! var entry2 = post(concatUrl('blogs', blog.id, 'entries'), {
title: 'my second post',
body: 'I do not know what to write any more...'
});
! var comment1 = all(entry1, visitor1).then(function(e1, v1) {
post('/comments', {
userId: v1.id,
entryId: e1.id,
text: "well written dude"
});
});
! var comment2 = all(entry1, visitor2).then(function(e1, v2) {
post('/comments', {
userId: v2.id,
entryId: e1.id,
text: "like it!"
});
});
! var comment3 = all(entry2, visitor2).then(function(e2, v2) {
post('/comments', {
userId: v2.id,
entryId: e2.id,
text: "nah, crap"
});
});
! all(comment1, comment2, comment3).then(function() {
get(concatUrl('blogs', blog.id)).then(function(blogInfo) {
assertEquals(blogInfo, {
name: 'My blog',
numberOfEntries: 2,
numberOfComments: 3
});
});
});
});
https://
github.com/
jakobmattsson/
z-presentation/
blob/master/
promises-in-out/
4-promises-convoluted.js
4
Note: without narration, this slide lacks a lot of
context. Open the file above and read the
commented version for the full story.
43. var blog = post('/blogs', {
name: 'My blog'
});
!var entry1 = post(concatUrl('blogs', blog.get('id'), 'entries'), {
title: 'my first post',
body: 'Here is the text of my first post'
});
!var entry2 = post(concatUrl('blogs', blog.get('id'), 'entries'), {
title: 'my second post',
body: 'I do not know what to write any more...'
});
!var visitor1 = post('/user', {
name: 'john doe'
});
!var visitor2 = post('/user', {
name: 'jane doe'
});
!var comment1 = post('/comments', {
userId: visitor1.get('id'),
entryId: entry1.get('id'),
text: "well written dude"
});
!var comment2 = post('/comments', {
userId: visitor2.get('id'),
entryId: entry1.get('id'),
text: "like it!"
});
!var comment3 = post('/comments', {
userId: visitor2.get('id'),
entryId: entry2.get('id'),
text: "nah, crap"
});
!var allComments = [comment1, comment2, comment2];
!var blogInfoUrl = concatUrl('blogs', blog.get('id'));
!var blogInfo = getAfter(blogInfoUrl, allComments);
!assertEquals(blogInfo, {
name: 'My blog',
numberOfEntries: 2,
numberOfComments: 3
});
https://
github.com/
jakobmattsson/
z-presentation/
blob/master/
promises-in-out/
5-promises-nice.js
5
Note: without narration, this slide lacks a lot of
context. Open the file above and read the
commented version for the full story.
44.
45. 1 Promises out: Always return promises -
not callback
2 Promises in: Functions should accept
promises as well as regular values
Three requirements
47. 1 Promises out: Always return promises -
not callback
2 Promises in: Functions should accept
promises as well as regular values
3 Promises between: Augment promises as
you augment regular objects
Three requirements
58. 1 Deep resolution: Resolve any kind of
object/array/promise/values/whatever
2 Make functions promise-friendly: Sync or
async doesn’t matter; will accept promises
3 Augmentation for promises: jQuery/
underscore/lodash-like extensions
What is Z?
59. Deep resolution
var data = {
userId: visitor1.get('id'),
entryId: entry1.get('id'),
text: 'well written dude'
};
!
Z(data).then(function(result) {
!
// result is now: {
// userId: 123,
// entryId: 456,
// text: 'well written dude'
// }
!
});
Takes any object
and resolves all
promises in it.
!
Like Q and Q.all,
but deep
1
60. Promise-friendly functions
var post = function(url, data, callback) {
// POSTs `data` to `url` and
// then invokes `callback`
};
!
post = Z.bindAsync(post);
!
var comment1 = post('/comments', {
userId: visitor1.get('id'),
entryId: entry1.get('id'),
text: 'well written dude'
});
bindAsync creates
a function that
takes promises as
arguments and
returns a promise.
2
61. Promise-friendly functions
var add = function(x, y) {
return x + y;
};
!
add = Z.bindSync(add);
!
var sum = add(v1.get('id'), e1.get('id'));
!
var comment1 = post('/comments', {
userId: visitor1.get('id'),
entryId: entry1.get('id'),
text: 'well written dude',
likes: sum
});
2
bindSync does that
same, for functions
that are not async
62. Augmentation for promises
var commentData = get('/comments/42');
!
var text = commentData.get('text');
!
var lowerCased = text.then(function(text) {
return text.toLowerCase();
});
3
Without
augmentation
every operation
has to be wrapped
in ”then”
63.
64. Augmentation for promises
Z.mixin({
toLowerCase: function() {
return this.value.toLowerCase();
}
});
!
var commentData = get('/comments/42');
!
commentData.get('text').toLowerCase();
3
Z has mixin to
solve this
!
Note that Z is not
explicitly applied
to the promise
66. 1 Promises out: Always return promises -
not callback
2 Promises in: Functions should accept
promises as well as regular values
3 Promises between: Augment promises as
you augment regular objects
Three requirements