Monthly Archives: January 2017

The Next Version of Angular is Angular v4

By jackykimani

nTLIaPEJSLaYXpwcRqOu_next-version-of-angular-is-angular-4.png.jpg

Angular will be making another big number upgrade to Angular v4. Don’t be afraid of the change though, Angular is still the Angular you’re learning to love. This is mainly a version numbering change and not a platform rewrite like Angular 1 to Angular v2.

The launch wasn’t just the final stage of Angular v2, rather it was the stage where they had something stable.

TLDR: Jump from v2 to v4 for Semver matching across packages. Angular is still Angular.

There were a number of minor releases after the launch of v2.0.0 which included:

  • v2.1 – router enhancements and route reloading
  • v2.2 – AoT(Ahead-of-Time) compatibility and ngUpgrade
  • v2.3 – improved language service used especially by IDE vendors. The service made it easy for IDEs to integrate with Typescript since they do not just ship the compiler. It also enables autocompletion on the IDEs and has better error handling by providing better error messages.

Semver

The Angular team announced that they will be using SEMVER when releasing updates.

SEMVER (Semantic Versioning) is basically about adding meaning to version numbers.

Sermver is pretty simple if you look at the chart below.

Basically what this means is that:

  1. Patch versions are released every week with the exception of holidays
  2. Minor versions are released every month
  3. Major versions are released every 6 months, meaning 2 major versions every year.

Angular is built on a monorepo, this simply means there is one huge repository on Github for all of Angular’s packages and all its work. Google also has all their work including Google Maps and all other Google products on one repository. This has its advantages and disadvantages

The Angular team feels confident about their monorepo design for the following reasons:

  • They release exact combinations of versions battle-tested at Google.
  • They are more productive this way and can get more stuff done

Switching from Angular v2 to Angular v4

Packages on the Angular repository have been following semver except the @angular/router package which has a one-off version, this, according to Angular, is a screw-up on their end, which is noble of them to admit that.

While the @angular/core and others were on version 2, the @angular/router was on version 3. This caused some confusion so the bump to Angular v4 matches all packages up nicely.

Upcoming features

Some of the features that Angular is looking to roll out in upcoming releases include:

Typescript compatibility

The Typescript team has been working on a number of improvements including:

  • Creating smarter compilers which handle errors better and give better error messages.
  • Implementing strictNullChecks to provide extra type safety

This means the Angular compiler (ngc) will be faster since they will be taking advantage of the optimizations of Typescript

It will be a breaking change for Angular since the current Typescript version (1.8) is not compatible with v2.1. This is because they edited some features and the type system is richer so it’s no longer compatible with Angular v2

Backwards compatibility with Angular v2

It will be able to successfully use interfaces and data from applications made with Angular v2

Better Angular compiler errors

The compiler will be much smarter in terms of error handling

Faster

The ngc will be faster in terms of runtime speed and parse time. It will also be smaller

Release schedule

Angular v4 is due in March 2017 but before then they released a schedule for their betas and rc (release candidate) versions which simply put, are beta versions with the potential to be a final product and which are ready to be released unless significant bugs emerge.

Angular is clearly evolving! To avoid a rough transition from one version to another like what happened with the transition from Angular 1 to Angular v2, Angular is trying to be:

  • Predictable
  • Transparent
  • Stable
  • Incremental

How? According to Igor Minar, Angular plans to have major releases every 6 months with minimal breaking changes. This seems like a pretty feasible plan, unless another mistake is done with the naming of the packages like it happened for the router package.

Naming convention

Angular has moved the attention from the version numbers when naming the different versions. They are adopting the following naming convention:

  • Angular 1 will be called AngularJS
  • Angular v2+ will just be called Angular

It’s just “Angular”

Conclusion

Angular is planning to bring in more updates but rather than having major changes at once, the plan is to make incremental, predictable and stable changes regularly. It will have support for libraries using Javascript and Typescipt just as it always has.

Finally, keep calm and embrace angular, don’t worry yourself about version numbers too much.

For more info on the release schedule, see:

Ok… let me explain: it’s going to be Angular v4.0, or just Angular

For more about this you can watch Igor Minar’s opening keynote:

Source:: scotch.io

What’s New in Laravel 5.4

By kayandrae

EQJ2v8nZSXu0Qa0jfbPG_whats-new-in-laravel-5.4.png.jpg

If you’ve been following Scotch for a while, you heard a lot about Laravel. Some months ago, Laravel 5.3 was released. It introduced new features like Mailables.

Yesterday, the 25th of January, Laravel 5.4 was released.

It comes with no surprise that it brought a lot of new and exciting features to Laravel, and for the remainder of this article, we shall go through the new features.

New Middlewares

With the release of 5.4, two new middlewares are now shipped with the framework. If you don’t know what middlewares are, check out Understanding Laravel Middlewares.

The middlewares are:

Trim Strings Middleware

Just as the name implies, this middleware trims extra spaces from request data. For example, a user submits their email through a form on your website and mistakenly types in some extra space after the email.

This middleware will automatically trim whitespace, so if a user submits something like this.

// 'demo@example.org     '

Because of the existence of this middleware (IlluminateFoundationHttpMiddlewareTrimStrings::class) in App/Kernel.php, it gets converted into.

// 'demo@example.org'

Convert Empty Strings to Null

Still, as the name implies, this middleware converts empty strings to null. So if a user submits an empty form instead of getting '' it gets converted to null.

Higher order messages

This is perhaps one of my favourite feature ever added to Laravel. It much easier to show than explain.

Imagine we have a collection of blog posts and we want to perform an operation on each item in the collection. Normally, we would do this.

Learn about Collections in Laravel.

// Loop through all the posts and schedule them for sharing to twitter
$posts->each(function ($post) {
    return $post->schedule(TWITTER);
});

With High order messages in Laravel, we can simplify the above code into this.

$posts->each->schedule(TWITTER);

Yes, this is now a possibility. It doesn’t just stop here either, we can take this a bit further and chain them. Here, another scenario.

/**
* Loop through all the posts and reject any archived post
* Then for the remaining posts, schedule each of them to twitter.
*/
$posts->reject(function ($post) {
    return $post->archived;
})->each(function ($post) {
    return $post->schedule(TWITTER);
});

With high order messages, we can simplify the above code into this.

$posts->reject->archived->each->schedule(TWITTER);

Want to see how it’s done, check out this commit. This is simply mindblowing

From Elixir to Mix

Laravel Elixir provided us with a gulp wrapper that made development and packaging of assets easier.

The next version of Laravel Elixir is changing the underlying system and will be built on Webpack, instead of Gulp. This will replace the plugin ecosystem, and because of such a significant change, it was time to rename the package.

Also, Laravel Mix comes with a new helper function called mix() that serves as a replacement to the former elixir() function.

If you have a project still using Elixir, you can continue using it, as it is still supported and not going anywhere anytime soon.

Fluent Routing

The Route facade in Laravel is now fluent. Previously, if we wanted to name a route, we would do this.

Route::get('user/{id}/profile', function ($id) {
    //
})->name('profile');

Now, we can do this.

Route::name('profile')->get('user/{id}/profile', function ($id) {
    // some closure action...
});

We could register a route name and a middleware

Route::name('users.index')->middleware('auth')->get('users', function () {
    // some closure action...
});

Registering a middleware with a route prefix and group

Route::middleware('auth')->prefix('api')->group(function () {
    // register some routes...
});

Registering a middleware to a resource controller

Route::middleware('auth')->resource('photo', 'PhotoController');

Components and Slots

Components and slots allow us to simplify HTML elements into reusable areas.

In our application, we usually have components like modals, notification panel etc. We can now define them as components and reuse them.

To create a component, we simply create a new blade file and refer to it using.

@component('path.to.blade.file')
    Modal text go in here
@endcomponent

You can read all about components and slots here.

Real-Time Facades

Facades provide a “static” interface to classes that are available in the application’s service container. Laravel ships with many facades which provide access to almost all of Laravel’s features. Laravel facades serve as “static proxies” to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

One example that comes to mind is Auth. In laravel, we access an authenticated user’s data by doing Auth::user(). This Auth class is a facade.

Now in Laravel 5.4, we can create facades on the fly. All we need do is namespace class on the Facade namespace and we can use the class as a facade.

namespace FacadeAppUser;

Doing this will automatically convert our User model into a facade.

Laravel dusk

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your machine. Instead, Dusk uses a standalone ChromeDriver installation. However, you are free to utilise any other Selenium compatible driver you wish.

Basically, it means we can test our Laravel code like we would in a web browser. Currently, Laravel uses browser-kit for testing.

The problem with browser-kit is that it is limited, and Dusk serves as an alternative with more features.

Dusk can detect AJAX etc. A full-length article on Dusk is on the way, stay tuned.

Fix: Specified key was too long error

Laravel 5.4 made a change to the default database character set, and it’s now utf8mb4 which includes support for storing emojis. This only affects new applications and as long as you are running MySQL v5.7.7 and higher you do not need to do anything.

For those running MariaDB or older versions of MySQL you may hit this error when trying to run migrations:

[IlluminateDatabaseQueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:

use IlluminateSupportFacadesSchema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Conclusion

Some features not explained above include

  • Resourceful Controller with Model Boilerplate: in simple terms, it is route model bindings for controllers.
  • JSON Based Language Files: this means that translation for text in Laravel can now be done with JSON files instead of PHP files. Learn More.
  • Markdown Mailables: this allows us to build Mailables in laravel using the Markdown syntax.
  • Map Eloquent Events to Dedicated Classes. Here is a video that further explains this.

If something was omitted, please let us know in the comment. Also, there is a free video series on Laracasts that shows What’s New in Laravel 5.4.

Source:: scotch.io

Build a RESTful JSON API With Rails 5 – Part One

By Austin Kabiru

dLryQn8cQzywlNK4fgUX_restful-json-api-in-ruby-on-rails.png.jpg

Rails is popularly known for building web applications. Chances are if you’re reading this you’ve built a traditional server-rendered web application with Rails before. If not, I’d highly recommend going through the Getting Started with Rails page to familiarize yourself with the Rails framework before proceeding with this tutorial.

As of version 5, Rails core now supports API only applications! In previous versions, we relied on an external gem: rails-api which has since been merged to core rails.

API only applications are slimmed down compared to traditional Rails web applications. According to Rails 5 release notes, generating an API only application will:

  • Start the application with a limited set of middleware
  • Make the ApplicationController inherit from ActionController::API instead of ActionController::Base
  • Skip generation of view files

This works to generate an API-centric framework excluding functionality that would otherwise be unused and unnecessary.

In this two-part tutorial, we’ll build a todo list API where users can manage their to-do lists and todo items.

Prerequisites

Before we begin, make sure you have ruby version >=2.2.2 and rails version 5.

$ ruby -v # ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin16]
$ rails -v # Rails 5.0.1

If your ruby version is not up to date, you can update it with a ruby version manager like rvm or rbenv.

# when using rbenv
$ rbenv install 2.3.1
# set 2.3.1 as the global version
$ rbenv global 2.3.1
# when using rvm
$ rvm install 2.3.1
# set 2.3.1 as the global version
$ rvm use 2.3.1

If your rails version is not up to date, update to the latest version by running:

$ gem update rails

All good? Let’s get started!

API Endpoints

Our API will expose the following RESTful endpoints.

Endpoint Functionality
POST /signup Signup
POST /auth/login Login
GET /auth/logout Logout
GET /todos List all todos
POST /todos Create a new todo
GET /todos/:id Get a todo
PUT /todos/:id Update a todo
DELETE /todos/:id Delete a todo and its items
GET /todos/:id/items Get a todo item
PUT /todos/:id/items Update a todo item
DELETE /todos/:id/items Delete a todo item

Part One will Cover:

  • Project setup
  • Todos API
  • TodoItems API

Project Setup

Generate a new project todos-api by running:

$ rails new todos-api --api -T

Note that we’re using the --api argument to tell Rails that we want an API application and -T to exclude Minitest the default
testing framework. Don’t freak out, we’re going to write tests. We’ll be using RSpec instead to test our API. I find RSpec to be more expressive
and easier to start with as compared to Minitest.

Dependencies

Let’s take a moment to review the gems that we’ll be using.

  • rspec-rails – Testing framework.
  • factory_girl_rails – A fixtures replacement with a more straightforward syntax. You’ll see.
  • shoulda_matchers – Provides RSpec with additional matchers.
  • database_cleaner – You guessed it! It literally cleans our test database to ensure
    a clean state in each test suite.
  • faker – A library for generating fake data. We’ll use this to generate test data.

All good? Great! Let’s set them up. In your Gemfile:

Add rspec-rails to both the :development and :test groups.

# Gemfile
group :development, :test do
  gem 'rspec-rails', '~> 3.5'
end

This is a handy shorthand to include a gem in multiple environments.

Add factory_girl_rails, shoulda_matchers, faker and database_cleaner to the :test group.

# Gemfile
group :test do
  gem 'factory_girl_rails', '~> 4.0'
  gem 'shoulda-matchers', '~> 3.1'
  gem 'faker'
  gem 'database_cleaner'
end

Install the gems by running:

$ bundle install

Initialize the spec directory (where our tests will reside).

$ rails generate rspec:install

This adds the following files which are used for configuration:

  • .rspec
  • spec/spec_helper.rb
  • spec/rails_helper.rb

Create a factories directory (factory girl uses this as the default directory). This is where we’ll define the model factories.

$ mkdir spec/factories

Configuration

In spec/rails_helper.rb

# require database cleaner at the top level
require 'database_cleaner'

# [...]
# configure shoulda matchers to use rspec as the test framework and full matcher libraries for rails
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end

# [...]
RSpec.configuration do |config|
  # [...]
  # add `FactoryGirl` methods
  config.include FactoryGirl::Syntax::Methods

  # start by truncating all the tables but then use the faster transaction strategy the rest of the time.
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
    DatabaseCleaner.strategy = :transaction
  end

  # start the transaction strategy as examples are run
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
  # [...]
end

Phew! That was a rather long. Good thing is, it’s a smooth ride from here on out.


Models

Let’s start by generating the Todo model

$ rails g model Todo title:string created_by:string

Notice that we’ve included the model attributes in the model generation command. This way we don’t have to edit the migration file.
The generator invokes active record and rspec to generate the migration, model, and spec respectively.

# db/migrate/[timestamp]_create_todos.rb
class CreateTodos < ActiveRecord::Migration[5.0]
  def change
    create_table :todos do |t|
      t.string :title
      t.string :created_by

      t.timestamps
    end
  end
end

And now the Item model

$ rails g model Item name:string done:boolean todo:references

By adding todo:references we’re telling the generator to set up an association with the Todo model.
This will do the following:

  • Add a foreign key column todo_id to the items table
  • Setup a belongs_to association in the Item model
# db/migrate/[timestamp]_create_items.rb
class CreateItems < ActiveRecord::Migration[5.0]
  def change
    create_table :items do |t|
      t.string :name
      t.boolean :done
      t.references :todo, foreign_key: true

      t.timestamps
    end
  end
end

Looks good? Let’s run the migrations.

$ rails db:migrate

We’re Test Driven, let’s write the model specs first.

# spec/models/todo_spec.rb
require 'rails_helper'

# Test suite for the Todo model
RSpec.describe Todo, type: :model do
  # Association test
  # ensure Todo model has a 1:m relationship with the Item model
  it { should have_many(:items).dependent(:destroy) }
  # Validation tests
  # ensure columns title and created_by are present before saving
  it { should validate_presence_of(:title) }
  it { should validate_presence_of(:created_by) }
end

RSpec has a very expressive DSL (Domain Specific Language). You can almost read the tests like a paragraph.
Remember our shoulda matchers gem? It provides RSpec with the nifty association and validation matchers above.

# spec/models/item_spec.rb
require 'rails_helper'

# Test suite for the Item model
RSpec.describe Item, type: :model do
  # Association test
  # ensure an item record belongs to a single todo record
  it { should belong_to(:todo) }
  # Validation test
  # ensure column name is present before saving
  it { should validate_presence_of(:name) }
end

Let’s execute the specs by running:

$ bundle exec rspec

And to no surprise, we have only one test passing and four failures. Let’s go ahead and fix the failures.

# app/models/todo.rb
class Todo < ApplicationRecord
  # model association
  has_many :items, dependent: :destroy

  # validations
  validates_presence_of :title, :created_by
end
# app/models/item.rb
class Item < ApplicationRecord
  # model association
  belongs_to :todo

  # validation
  validates_presence_of :name
end

At this point run the tests again and…

voila! All green.


Controllers

Now that our models are all setup, let’s generate the controllers.

$ rails g controller Todos
$ rails g controller Items

You guessed it! Tests first… with a slight twist. Generating controllers by default generates controller specs.
However, we won’t be writing any controller specs. We’re going to write request specs instead.

Request specs are designed to drive behavior through the full stack, including routing. This means they can hit the applications’
HTTP endpoints as opposed to controller specs which call methods directly. Since we’re building an API application, this is exactly the kind of behavior we want from our tests.

According to RSpec, the official recommendation of the Rails team and the RSpec core team is to write request specs instead.

Add a requests folder to the spec directory with the corresponding spec files.

$ mkdir spec/requests && touch spec/requests/{todos_spec.rb,items_spec.rb} 

Before we define the request specs, Let’s add the model factories which will provide the test data.

Add the factory files:

$ touch spec/factories/{todos.rb,items.rb}

Define the factories.

# spec/factories/todos.rb
FactoryGirl.define do
  factory :todo do
    title { Faker::Lorem.word }
    created_by { Faker::Number.number(10) }
  end
end

By wrapping faker methods in a block, we ensure that faker generates dynamic data every time the factory is invoked.
This way, we always have unique data.

# spec/factories/items.rb
FactoryGirl.define do
  factory :item do
    name { Faker::StarWars.character }
    done false
    todo_id nil
  end
end

Todo API

# spec/requests/todos_spec.rb
require 'rails_helper'

RSpec.describe 'Todos API', type: :request do
  # initialize test data 
  let!(:todos) { create_list(:todo, 10) }
  let(:todo_id) { todos.first.id }

  # Test suite for GET /todos
  describe 'GET /todos' do
    # make HTTP get request before each example
    before { get '/todos' }

    it 'returns todos' do
      # Note `json` is a custom helper to parse JSON responses
      expect(json).not_to be_empty
      expect(json.size).to eq(10)
    end

    it 'returns status code 200' do
      expect(response).to have_http_status(200)
    end
  end

  # Test suite for GET /todos/:id
  describe 'GET /todos/:id' do
    before { get "/todos/#{todo_id}" }

    context 'when the record exists' do
      it 'returns the todo' do
        expect(json).not_to be_empty
        expect(json['id']).to eq(todo_id)
      end

      it 'returns status code 200' do
        expect(response).to have_http_status(200)
      end
    end

    context 'when the record does not exist' do
      let(:todo_id) { 100 }

      it 'returns status code 404' do
        expect(response).to have_http_status(404)
      end

      it 'returns a not found message' do
        expect(response.body).to match(/Couldn't find Todo/)
      end
    end
  end

  # Test suite for POST /todos
  describe 'POST /todos' do
    # valid payload
    let(:valid_attributes) { { title: 'Learn Elm', created_by: '1' } }

    context 'when the request is valid' do
      before { post '/todos', params: valid_attributes }

      it 'creates a todo' do
        expect(json['title']).to eq('Learn Elm')
      end

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

    context 'when the request is invalid' do
      before { post '/todos', params: { title: 'Foobar' } }

      it 'returns status code 422' do
        expect(response).to have_http_status(422)
      end

      it 'returns a validation failure message' do
        expect(response.body)
          .to match(/Validation failed: Created by can't be blank/)
      end
    end
  end

  # Test suite for PUT /todos/:id
  describe 'PUT /todos/:id' do
    let(:valid_attributes) { { title: 'Shopping' } }

    context 'when the record exists' do
      before { put "/todos/#{todo_id}", params: valid_attributes }

      it 'updates the record' do
        expect(response.body).to be_empty
      end

      it 'returns status code 204' do
        expect(response).to have_http_status(204)
      end
    end
  end

  # Test suite for DELETE /todos/:id
  describe 'DELETE /todos/:id' do
    before { delete "/todos/#{todo_id}" }

    it 'returns status code 204' do
      expect(response).to have_http_status(204)
    end
  end
end

We start by populating the database with a list of 10 todo records (thanks to factory girl).
We also have a custom helper method json which parses the JSON response to a Ruby Hash which is easier to work with in our tests.
Let’s define it in spec/support/request_spec_helper.

Add the directory and file:

$ mkdir spec/support && touch spec/support/request_spec_helper.rb
# spec/support/request_spec_helper
module RequestSpecHelper
  # Parse JSON response to ruby hash
  def json
    JSON.parse(response.body)
  end
end

The support directory is not autoloaded by default. To enable this, open the rails helper and comment out the support directory auto-loading and then
include it as shared module for all request specs in the RSpec configuration block.

# spec/rails_helper.rb
# [...]
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# [...]
RSpec.configuration do |config|
  # [...]
  config.include RequestSpecHelper, type: :request
  # [...]
end

Run the tests.

We get failing routing errors. This is because we haven’t defined the routes yet. Go ahead and define them in config/routes.rb.

# config/routes.rb
Rails.application.routes.draw do
  resources :todos do
    resources :items
  end
end

In our route definition, we’re creating todo resource with a nested items resource. This enforces the 1:m (one to many) associations at the routing level.
To view the routes, you can run:

$ rails routes

When we run the tests we see that the routing error is gone. As expected we have controller failures. Let’s go ahead and define the controller methods.

# app/controllers/todos_controller.rb
class TodosController < ApplicationController
  before_action :set_todo, only: [:show, :update, :destroy]

  # GET /todos
  def index
    @todos = Todo.all
    json_response(@todos)
  end

  # POST /todos
  def create
    @todo = Todo.create!(todo_params)
    json_response(@todo, :created)
  end

  # GET /todos/:id
  def show
    json_response(@todo)
  end

  # PUT /todos/:id
  def update
    @todo.update(todo_params)
    head :no_content
  end

  # DELETE /todos/:id
  def destroy
    @todo.destroy
    head :no_content
  end

  private

  def todo_params
    # whitelist params
    params.permit(:title, :created_by)
  end

  def set_todo
    @todo = Todo.find(params[:id])
  end
end

More helpers. Yay! This time we have:

  • json_response which does… yes, responds with JSON and an HTTP status code (200 by default).
    We can define this method in concerns folder.
# app/controllers/concerns/response.rb
module Response
  def json_response(object, status = :ok)
    render json: object, status: status
  end
end
  • set_todo – callback method to find a todo by id. In the case where the record does not exist, ActiveRecord
    will throw an exception ActiveRecord::RecordNotFound. We’ll rescue from this exception and return a 404 message.
# app/controllers/concerns/exception_handler.rb
module ExceptionHandler
  # provides the more graceful `included` method
  extend ActiveSupport::Concern

  included do
    rescue_from ActiveRecord::RecordNotFound do |e|
      json_response({ message: e.message }, :not_found)
    end

    rescue_from ActiveRecord::RecordInvalid do |e|
      json_response({ message: e.message }, :unprocessable_entity)
    end
  end
end

In our create method in the TodosController, note that we’re using create! instead of create. This way, the model will raise
an exception ActiveRecord::RecordInvalid. This way, we can avoid deep nested if statements in the controller. Thus, we rescue from this exception
in the ExceptionHandler module.

However, our controller classes don’t know about these helpers yet. Let’s fix that by including these modules in the
application controller.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::API
  include Response
  include ExceptionHandler
end

Run the tests and everything’s all green!

Let’s fire up the server for some good old manual testing.

$ rails s

Now let’s go ahead and make requests to the API. I’ll be using httpie as my HTTP client.

# GET /todos
$ http :3000/todos
# POST /todos
$ http POST :3000/todos title=Mozart created_by=1
# PUT /todos/:id
$ http PUT :3000/todos/1 title=Beethoven
# DELETE /todos/:id
$ http DELETE :3000/todos/1

You should see similar output.


TodoItems API

# app/requests/items_spec.rb
require 'rails_helper'

RSpec.describe 'Items API' do
  # Initialize the test data
  let!(:todo) { create(:todo) }
  let!(:items) { create_list(:item, 20, todo_id: todo.id) }
  let(:todo_id) { todo.id }
  let(:id) { items.first.id }

  # Test suite for GET /todos/:todo_id/items
  describe 'GET /todos/:todo_id/items' do
    before { get "/todos/#{todo_id}/items" }

    context 'when todo exists' do
      it 'returns status code 200' do
        expect(response).to have_http_status(200)
      end

      it 'returns all todo items' do
        expect(json.size).to eq(20)
      end
    end

    context 'when todo does not exist' do
      let(:todo_id) { 0 }

      it 'returns status code 404' do
        expect(response).to have_http_status(404)
      end

      it 'returns a not found message' do
        expect(response.body).to match(/Couldn't find Todo/)
      end
    end
  end

  # Test suite for GET /todos/:todo_id/items/:id
  describe 'GET /todos/:todo_id/items/:id' do
    before { get "/todos/#{todo_id}/items/#{id}" }

    context 'when todo item exists' do
      it 'returns status code 200' do
        expect(response).to have_http_status(200)
      end

      it 'returns the item' do
        expect(json['id']).to eq(id)
      end
    end

    context 'when todo item does not exist' do
      let(:id) { 0 }

      it 'returns status code 404' do
        expect(response).to have_http_status(404)
      end

      it 'returns a not found message' do
        expect(response.body).to match(/Couldn't find Item/)
      end
    end
  end

  # Test suite for PUT /todos/:todo_id/items
  describe 'POST /todos/:todo_id/items' do
    let(:valid_attributes) { { name: 'Visit Narnia', done: false } }

    context 'when request attributes are valid' do
      before { post "/todos/#{todo_id}/items", params: valid_attributes }

      it 'returns status code 201' do
        expect(response).to have_http_status(201)
      end
    end

    context 'when an invalid request' do
      before { post "/todos/#{todo_id}/items", params: {} }

      it 'returns status code 422' do
        expect(response).to have_http_status(422)
      end

      it 'returns a failure message' do
        expect(response.body).to match(/Validation failed: Name can't be blank/)
      end
    end
  end

  # Test suite for PUT /todos/:todo_id/items/:id
  describe 'PUT /todos/:todo_id/items/:id' do
    let(:valid_attributes) { { name: 'Mozart' } }

    before { put "/todos/#{todo_id}/items/#{id}", params: valid_attributes }

    context 'when item exists' do
      it 'returns status code 204' do
        expect(response).to have_http_status(204)
      end

      it 'updates the item' do
        updated_item = Item.find(id)
        expect(updated_item.name).to match(/Mozart/)
      end
    end

    context 'when the item does not exist' do
      let(:id) { 0 }

      it 'returns status code 404' do
        expect(response).to have_http_status(404)
      end

      it 'returns a not found message' do
        expect(response.body).to match(/Couldn't find Item/)
      end
    end
  end

  # Test suite for DELETE /todos/:id
  describe 'DELETE /todos/:id' do
    before { delete "/todos/#{todo_id}/items/#{id}" }

    it 'returns status code 204' do
      expect(response).to have_http_status(204)
    end
  end
end

As expected, running the tests at this point should output failing todo item tests. Let’s define the todo items controller.

# app/controllers/items_controller.rb
class ItemsController < ApplicationController
  before_action :set_todo
  before_action :set_todo_item, only: [:show, :update, :destroy]

  # GET /todos/:todo_id/items
  def index
    json_response(@todo.items)
  end

  # GET /todos/:todo_id/items/:id
  def show
    json_response(@item)
  end

  # POST /todos/:todo_id/items
  def create
    @todo.items.create!(item_params)
    json_response(@todo, :created)
  end

  # PUT /todos/:todo_id/items/:id
  def update
    @item.update(item_params)
    head :no_content
  end

  # DELETE /todos/:todo_id/items/:id
  def destroy
    @item.destroy
    head :no_content
  end

  private

  def item_params
    params.permit(:name, :done)
  end

  def set_todo
    @todo = Todo.find(params[:todo_id])
  end

  def set_todo_item
    @item = @todo.items.find_by!(id: params[:id]) if @todo
  end
end

Run the tests.

Run some manual tests for the todo items API:

# GET /todos/:todo_id/items
$ http :3000/todos/2/items
# POST /todos/:todo_id/items
$ http POST :3000/todos/2/items name='Listen to 5th Symphony' done=false
# PUT /todos/:todo_id/items/:id
$ http PUT :3000/todos/2/items/1 done=true
# DELETE /todos/:todo_id/items/1
$ http DELETE :3000/todos/2/items/1


Conclusion

That’s it for part one! At this point you should have learned how to:

  • Generate an API application with Rails 5
  • Setup RSpec testing framework with Factory Girl, Database Cleaner, Shoulda Matchers and Faker.
  • Build models and controllers with TDD (Test Driven Development).
  • Make HTTP requests to an API with httpie.

In the next part, we’ll cover authentication with JWT, pagination, and API versioning. Hope to see you there. Cheers!

Source:: scotch.io

The Next Version of Angular is Angular 4

By Jacky Kimani

nTLIaPEJSLaYXpwcRqOu_next-version-of-angular-is-angular-4.png.jpg

Angular will be making another big number upgrade to Angular 4. Don’t be afraid of the change though, Angular is still the Angular you’re learning to love. This is mainly a version numbering change and not a platform rewrite like Angular 1 to Angular 2.

The launch wasn’t just the final stage of Angular 2, rather it was the stage where they had something stable.

TLDR: Jump from 2 to 4 for Semver matching across packages. Angular is still Angular.

There were a number of minor releases after the launch of 2.0.0 which included:

  • 2.1 – router enhancements and route reloading
  • 2.2 – AoT(Ahead-of-Time) compatibility and ngUpgrade
  • 2.3 – improved language service used especially by IDE vendors. The service made it easy for IDEs to integrate with Typescript since they do not just ship the compiler. It also enables autocompletion on the IDEs and has better error handling by providing better error messages.

Semver

The Angular team announced that they will be using SEMVER when releasing updates.

SEMVER (Semantic Versioning) is basically about adding meaning to version numbers.

Sermver is pretty simple if you look at the chart below.

Basically what this means is that:

  1. Patch versions are released every week with the exception of holidays
  2. Minor versions are released every month
  3. Major versions are released every 6 months, meaning 2 major versions every year.

Angular is built on a monorepo, this simply means there is one huge repository on Github for all of Angular’s packages and all its work. Google also has all their work including Google Maps and all other Google products on one repository. This has its advantages and disadvantages

The Angular team feels confident about their monorepo design for the following reasons:

  • They release exact combinations of versions battle-tested at Google.
  • They are more productive this way and can get more stuff done

Switching from Angular 2 to Angular 4

Packages on the Angular repository have been following semver except the @angular/router package which has a one-off version, this, according to Angular, is a screw-up on their end, which is noble of them to admit that.

While the @angular/core and others were on version 2, the @angular/router was on version 3. This caused some confusion so the bump to Angular 4 matches all packages up nicely.

Upcoming features

Some of the features that Angular is looking to roll out in upcoming releases include:

Typescript compatibility

The Typescript team has been working on a number of improvements including:

  • Creating smarter compilers which handle errors better and give better error messages.
  • Implementing strictNullChecks to provide extra type safety

This means the Angular compiler (ngc) will be faster since they will be taking advantage of the optimizations of Typescript

It will be a breaking change for Angular since the current Typescript version (1.8) is not compatible with 2.1. This is because they edited some features and the type system is richer so it’s no longer compatible with Angular 2

Backwards compatibility with Angular 2

It will be able to successfully use interfaces and data from applications made with Angular 2

Better Angular compiler errors

The compiler will be much smarter in terms of error handling

Faster

The ngc will be faster in terms of runtime speed and parse time. It will also be smaller

Release schedule

Angular 4 is due in March 2017 but before then they released a schedule for their betas and rc (release candidate) versions which simply put, are beta versions with the potential to be a final product and which are ready to be released unless significant bugs emerge.

Angular is clearly evolving! To avoid a rough transition from one version to another like what happened with the transition from Angular 1 to Angular 2, Angular is trying to be:

  • Predictable
  • Transparent
  • Stable
  • Incremental

How? According to Igor Minar, Angular plans to have major releases every 6 months with minimal breaking changes. This seems like a pretty feasible plan, unless another mistake is done with the naming of the packages like it happened for the router package.

Naming convention

Angular has moved the attention from the version numbers when naming the different versions. They are adopting the following naming convention:

  • Angular 1 will be called AngularJS
  • Angular 2+ will just be called Angular

It’s just “Angular”

Conclusion

Angular is planning to bring in more updates but rather than having major changes at once, the plan is to make incremental, predictable and stable changes regularly. It will have support for libraries using Javascript and Typescipt just as it always has.

Finally, keep calm and embrace angular, don’t worry yourself about version numbers too much.

For more info on the release schedule, see:

Ok… let me explain: it’s going to be Angular 4.0, or just Angular

For more about this you can watch Igor Minar’s opening keynote:

Source:: scotch.io

Build a Music Player with Angular & Electron III : Bringing It All Together

By codebeast

qQqlNzPgRuWgBLfTyosW_build-a-music-app-with-angular-electron-part-3.jpg

This post is the last part of “Build a Music Player with Angular and Electron.” In the previous post we discussed presentation components which are also known as UI components. We were able to build out the UI for our app from start to finish but then users don’t consume pretty UI. Users will always want behavior in as much as they appreciate a good looking app.

In this last post, we are going bring everything we have done together using a container component and abstracting data request and handling to injectable services.

As a quick reminder, the image shows what we are up to:

Injectable Services

Before we dive into building the container component, let’s prepare the components’ dependencies which are services that will handle few utility tasks including network requests and playing sounds with the browser’s audio API.

API Service

The API service completes a very simple task — makes a get request to Soundcloud depending all the url passed to it while attaching a client Id to the request:

// ./src/app/music/shared/api.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ApiService {

    clientId = '[CLIENT_ID]'

    constructor(
      private http: Http
    ) {}

    get(url, attachClientId?) {
      // Should attach client id if the attachToken
      // is true
      let u;
      attachClientId ? u = this.prepareUrl(url) : u = url;
      // Returns an obsrevable
      // for the HTTP get request
      return this.http.get(u);
    }

    prepareUrl(url) {
      //Attach client id to stream url
      return `${url}?client_id=${this.clientId}`
    }

}

The prepareUrl method attaches the client Id to the URL so when a GET request is made, the get method checks if the attachClient flag is raised and calls prepareUrl based the flag condition.

Music Service

One more service we will need is the service that talks to API Service as well as use the audio API to play songs based on the feedback form the API Service:

// ./src/app/music/shared/music.service.ts
import { Injectable } from '@angular/core';
import { ApiService } from './api.service';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Injectable()
export class MusicService {

  audio;

  constructor(
    private apiService: ApiService
  ) {
    this.audio = new Audio();
  }

  load(url) {
    this.audio.src = this.apiService.prepareUrl(url);
    this.audio.load();
  }

  play(url) {
    this.load(url);
    this.audio.play()
  }

  getPlaylistTracks () {
      //Request for a playlist via Soundcloud using a client id
      return this.apiService.get('https://api.soundcloud.com/playlists/209262931', true)
        .map(res => res.json())
        .map(data => data.tracks);
  }

  randomTrack(tracks) {
    const trackLength = tracks.length;
    // Pick a random number
    const randomNumber = Math.floor((Math.random() * trackLength) + 1);
    // Return a random track
    return tracks[randomNumber];
  }

  formatTime(seconds) {
    let minutes:any = Math.floor(seconds / 60);
    minutes = (minutes >= 10) ? minutes : "0" + minutes;
    seconds = Math.floor(seconds % 60);
    seconds = (seconds >= 10) ? seconds : "0" + seconds;
    return minutes + ":" + seconds;
  }

  findTracks(value) {
    return this.apiService.get(`${this.apiService.prepareUrl('https://api.soundcloud.com/tracks')}&q=${value}`, false)
      .debounceTime(300)
      .distinctUntilChanged()
      .map(res => res.json())
  }

  xlArtwork(url) {
    return url.replace(/large/, 't500x500');
  }

}

Let’s walk through what this service by discussing each of the methods.

First things first, when the service is initialized, the audio API is set up by instantiating it and setting the instance to audio property on the class.

The load and play methods call the audio API’s load and play methods as well as passing in a URL to be loaded and played.

The app is expected to load a random song and play the song when the app starts. I created a playlist (which you can of course replace) and using getPlaylistTracks to fetch the playlist’s tracks. randomTrack is used to shuffle these tracks and pick one from the tracks to play.

formatTime method prepares the time so it can be displayed by the progress elapsed and total properties while xlArtwork generates a large image of the track artwork. We will see where the artwork is useful later in this post.

Finally, the findTracks will be utilized by the search component to search for tracks. The interesting thing about this method is that the returned observable is operated on with debounceTime to wait for 300ms interval between each request and distinctUntilChange to not repeat a request for the same values. These are great performance strategies.

App Component (Container Component)

Now to the real meat. The app component will serve as our container component, and with time we will see how the numbers add up.

What Happens when App Starts?

As mentioned earlier, while building our services, the plan is to play a random track from a given playlist when the app loads. To achieve this, we need to utilize Angular’s lifecycle hook, ngOnInit which is a lifecycle method called when the component is ready:

// ./src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { MusicService } from './music/shared/music.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  tracks: any[] = [];

  constructor(
    private musicService: MusicService
  ){}

  ngOnInit() {
    this.musicService.getPlaylistTracks().subscribe(tracks => {
      this.tracks = tracks;
      this.handleRandom();
    });

    // On song end
    this.musicService.audio.onended = this.handleEnded.bind(this);
    // On play time update
    this.musicService.audio.ontimeupdate = this.handleTimeUpdate.bind(this);
  }
}

MusicService is the only service we are injecting because the APIService is already used by MusicService for whatever we need the API service for.

The AppComponent class must implement OnInit so as to make use of the ngOnInit hook. The hook uses music service’s getPlaylistTracks to get a list of tracks, set the tracks property to the returned list, and call the handleRandom method which we are yet to create.

We also set up two events — what happens when a song ends and when the playing time updates. The events are passed handlers which we are yet to create too.

Random Tracks

The handleRandom method being used in the hook above is what we will create now. This method plucks a random song from the tracks property and plays the plucked song:

// . . .
export class AppComponent implements OnInit {
  title;
  tracks: any[] = [];
  backgroundStyle;

  //. . .

  handleRandom() {
    // Pluck a song
    const randomTrack = this.musicService.randomTrack(this.tracks);
    // Play the plucked song
    this.musicService.play(randomTrack.stream_url)
    // Set the title property
    this.title = randomTrack.title;
    // Create a background based on the playing song
    this.backgroundStyle = this.composeBackgroundStyle(randomTrack.artwork_url)
  }
}

One other thing that the method does is to set the title property for DetailsComponent which is the UI component that displays the title of the playing song. The method also set’s a backgroundStyle property which is dynamically updates the background image of the app with the playing track’s URL. composeBackgroundStyle returns the style object based on the image URL:

 composeBackgroundStyle(url) {
      return {
        width: '100%',
        height: '600px',
        backgroundSize:'cover',
        backgroundImage: `linear-gradient(
      rgba(0, 0, 0, 0.7),
      rgba(0, 0, 0, 0.7)
    ),   url(${this.musicService.xlArtwork(url)})`
      }
  }

The style is set on the template using NgStyle directive:

<!-- ./src/app/app.component.html -->
<div [ngStyle]="backgroundStyle">
</div>

Progress with Audio Events

When the component was initialized, we did set up some events for playing time update and song end. The handlers for these events were not created, let’s do that now:

// . . .
export class AppComponent implements OnInit{
  title;
  position;
  elapsed;
  duration;
  tracks: any[] = [];
  backgroundStyle;

  constructor(
    private musicService: MusicService
  ){}

  ngOnInit() {
    // . . .
    this.musicService.audio.onended = this.handleEnded.bind(this);
    this.musicService.audio.ontimeupdate = this.handleTimeUpdate.bind(this);
  }

  // . . .

  handleEnded(e) {
    this.handleRandom();
  }

  handleTimeUpdate(e) {
    const elapsed =  this.musicService.audio.currentTime;
    const duration =  this.musicService.audio.duration;
    this.position = elapsed / duration;
    this.elapsed = this.musicService.formatTime(elapsed);
    this.duration = this.musicService.formatTime(duration);
  }
}

onended event is handled by handleEnded. The handler is very simple; it just calls the handleRandom method to shuffle and pluck a song.

ontimeupdate is called at intervals when the song is playing. So it’s the perfect event to hook in and update our progress bar as well as the elapsed and total play time. This is why we are updating the the position, elapsed and duration properties which are passed down to the ProgressComponent.

Search Component Events & Properties

The search component demands values for it’s tracks property, and event handlers for it’s query and update events. These properties and events were created in the previous article.

The query event handle will be called handleQuery and will set the SearchComponent‘s tracks property using AppComponents‘s filteredTracks:

// . . .
export class AppComponent implements OnInit{
  // . . .
  filteredTracks: any[] = [];

  constructor(
    private musicService: MusicService
  ){}

  // . . .

  handleQuery(payload) {
      this.musicService.findTracks(payload).subscribe(tracks => {
        this.filteredTracks = tracks;
      });
  }
}

The handleQuery method uses MusicService‘s findTracks to find tracks that match the text being entered in the search text box and then sets filteredTracks to the fetched tracks. filteredTracks is what is passed as the value of tracks to the SearchComponent.

The handleUpdate is called when the autocomplete’s suggestion is clicked. The handler plays the selected item:

// . . .
export class AppComponent implements OnInit{
  // . . .
  filteredTracks: any[] = [];

  constructor(
    private musicService: MusicService
  ){}

  // . . .

  handleQuery(payload) {
      this.musicService.findTracks(payload).subscribe(tracks => {
        this.filteredTracks = tracks;
      });
  }
}

Player Events & Properties

The player UI component has more events than the rest of the components. It just has one property, paused which is a boolean to check if a song is paused or playing.

Player: Pause & Play

The pause and play action are controlled by one event, and the paused flag property is used to check the playing status of a song and act accordingly:

// . . .
export class AppComponent implements OnInit{
  // . . .
  paused = true;

  constructor(
    private musicService: MusicService
  ){}

  // . . .

  handlePausePlay() {
      if(this.musicService.audio.paused) {
        this.paused = true;
        this.musicService.audio.play()
      } else {
        this.paused = false;
        this.musicService.audio.pause()
      }
  }
}

The handler checks if the song is paused and plays the song. Otherwise the reverse is the case.

Player: Stop

The stop events resets the song to beginning:

// . . .
export class AppComponent implements OnInit{
  // . . .

  constructor(
    private musicService: MusicService
  ){}

  // . . .

  handleStop() {
    this.musicService.audio.pause();
    this.musicService.audio.currentTime = 0;
    this.paused = false;
  }
}

It’s just a trick. We pause the song, reset the time to beginning (0) and turn the paused flag down.

Player: Backward & Forward

The backward and forward events are used to rewind or fast forward the song based on a given interval:

// . . .
export class AppComponent implements OnInit{
  // . . .

  constructor(
    private musicService: MusicService
  ){}

  // . . .

  handleBackward() {
    let elapsed =  this.musicService.audio.currentTime;
    console.log(elapsed);
    if(elapsed >= 5) {
      this.musicService.audio.currentTime = elapsed - 5;
    }
  }

  handleForward() {
    let elapsed =  this.musicService.audio.currentTime;
    const duration =  this.musicService.audio.duration;
    if(duration - elapsed >= 5) {
      this.musicService.audio.currentTime = elapsed + 5;
    }
  }
}

For backward, we first check if we are 5 seconds into the song before attempting to take it back 5 seconds and for forward we check if we have up to 5 seconds left to be played in the song before trying to push it forward.

Player: Random

The random event just calls the random handler we created earlier to manually pluck a random track and play.

App Component Template

The app component template assembles all the UI component while passing them their respective properties and event handlers. It is also wrapped by a div which takes the NgStyle directive for dynamic background images.

<!-- ./src/app/app.component.html -->
<div [ngStyle]="backgroundStyle">
  <music-search
    (query)="handleQuery($event)"
    (update)="handleUpdate($event)"
    [tracks]="filteredTracks"
  ></music-search>

  <music-details
    [title]="title"
  ></music-details>

  <music-player
    (random)="handleRandom($event)"
    (backward)="handleBackward()"
    (forward)="handleForward()"
    (pauseplay)="handlePausePlay()"
    (stop)="handleStop()"
    [paused]="paused"
  ></music-player>

  <music-progress
    [current]="position"
    [elapsed]="elapsed"
    [total]="duration"
  ></music-progress>

  <music-footer></music-footer>

</div>

Conclusion

There are two important things to take home from this long journey — how components interact and code reuse. We were able to divide and conquer by using different levels of component which come together to make an awesome product.

You must have noticed how many times a member of the music or API service got called and how many times we called handleRandom. If not for good structure which is cheap to afford, we would have got ourselves in a deep mess and probably given up on the just completed journey.

Source:: scotch.io

20 Awesome PHP Libraries For Early 2017

By Danny Markov

20-php-libraries-early-2017

This week we have for you a collection of high-quality PHP libraries that have caught our eye in the last couple of months. We’ve tried our best to include projects that are active, well documented, and will have a realistic shot at finding a place in your developer’s workbelt.

If we’ve haven’t included your favorite new library, feel free to share it in the comments 🙂


Requests for PHP

A no-dependencies library that lets you send HTTP requests. It provides the needed methods for adding headers, accessing response data, handling forms, and everything else you may need, neatly packaged in a clean and easy to use API.

$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);

var_dump($request->status_code);
// int(200)

var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"

var_dump($request->body);
// string(26891) "[...]"

Rinvex Country

Rinvex Country is a PHP package that lets developers retrieve detailed information about the countries of the world. Using the over 50 methods you can get the area of Angola, the currency of Cyprus, the native name of Namibia or even the FIFA name of Finland. There is a ton of info available and the data sources are pretty reliable.

$egypt = country('eg');

$egypt->getCapital();   // Cairo
$egypt->getDemonym();   // Egyptian
$egypt->getTld();       // .eg
$egypt->getContinent(); // Africa
$egypt->getSubregion(); // Northern Africa
$egypt->getBorders();   // ["ISR","LBY","SDN"]

Botman

A PHP library for developing messenger bots. Works with most of the popular messaging platforms including Facebook Messenger, Slack, Telegram, WeChat, and others. There is also a helpful boilerplate Laravel project available here.

// create an instance
$botman = BotManFactory::create($config);

// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot) {
    $bot->reply('Hello yourself.');
});

// start listening
$botman->listen();

If you are not familiar with the concept of messenger bots we suggest you check out our article Developer’s Introduction To Chatbots.


Charts

Laravel package for generating highly customizable charts out of datasets. The package works as a PHP wrapper for multiple built-in JavaScript chart libraries, allowing devs to create a wide variety of graphs, gauges and progressbars using only one tool.

$chart = Charts::create('line', 'highcharts')
    ->view('custom.line.chart.view') 
    ->title('My nice chart')
    ->labels(['First', 'Second', 'Third'])
    ->values([5,10,20])
    ->dimensions(1000,500)
    ->responsive(false);

Swap

Swap allows you to retrieve currency exchange rates from a number of services such as Fixer, Google, and Yahoo. Request responses can be easily cached and accessed later. The library is available in the form of a Laravel Package as well.

// Build Swap with Fixer.io
$swap = (new Builder())
    ->add('fixer')
    ->build();
    
// Get the latest EUR/USD rate
$rate = $swap->latest('EUR/USD');

// 1.129
$rate->getValue();

// Get the EUR/USD rate 15 days ago
$rate = $swap->historical('EUR/USD', (new DateTime())->modify('-15 days'));

Math PHP

A collection of mathematical functions and algorithms ranging from simple algebra to finances, statistics, numerical analysis and others fields. The library is modular, has a straightforward API, and doesn’t require any external dependencies.

// Factors of an integer
$factors = Algebra::factors($n);

// Fibonacci sequence
$fib = Advanced::fibonacci($n);

// Combinations
$nCk  = Combinatorics::combinations($n, $k);

// Likelihood ratios
$LL = Experiment::likelihoodRatio($a, $b, $c, $d);

PHPUnit

PHPUnit is an advanced testing framework that enables teams to thoroughly test their code. Unit tests are written in standalone object-oriented classes with the help of many methods for handling assertions, dependencies, etc. A simple CLI is provided for running test and generating reports.

class StackTest extends TestCase
{
    public function testPushAndPop()
    {
        $stack = [];
        $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this->assertEquals('foo', $stack[count($stack)-1]);
        $this->assertEquals(1, count($stack));

        $this->assertEquals('foo', array_pop($stack));
        $this->assertEquals(0, count($stack));
    }
}

Atoum

A less popular testing framework we also wanted to share. Atoum offers a one-step installation precess and a relatively simple workflow, while still maintaining a ton of great features. It has a mock engine, expressive assertions, and a CLI that can execute multiple tests in parallel.

$this->given($testedInstance = new testedClass())
    ->and($testedClass[] = $firstValue = uniqid())
    ->then
        ->sizeof($testedInstance)->isEqualTo(1)
        ->string($testedClass[0])->isEqualTo($firstValue);

Simple Regex Language

A PHP implementation of the Simple Regex Language – a verbose way of writing regular expressions. The library provides multiple methods that can be chained together, forming readable and easy to understand RegEx rules. The library has ports for JavaScript and Python as well.

$query = SRL::startsWith()
    ->anyOf(function (Builder $query) {
        $query->digit()
            ->letter()
            ->oneOf('._%+-');
    })->onceOrMore()
    ->literally('@')
    ->anyOf(function (Builder $query) {
        $query->digit()
            ->letter()
            ->oneOf('.-');
    })->onceOrMore()
    ->literally('.')
    ->letter()->atLeast(2)
    ->mustEnd()->caseInsensitive();

Stash

Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like database queries or calls to external APIs, take a lot of time to run but tend to have the same results over short periods of time. This makes it much more efficient to store the results and call them back up later.

$pool = $this->cachePool;

// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");

// Get the data from it, if any happens to be there.
$userInfo = $item->get();

// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if($item->isMiss())
{
    // Run the relatively expensive code.
    $userInfo = loadUserInfoFromDatabase($userId);

    // Set the new value in $item.
    $item->set($userInfo);

    // Store the expensive code so the next time it doesn't miss.
    $pool->save($item)
}

PHP VCR

A port of the popular Ruby library for testing HTTP interactions. PHP VCR records HTTP requests and stores them in “cassettes” which can be replayed later on. A set of testing utilities are also provided, making it possible to inspect and compare recordings in detail.

// After turning on, the VCR will intercept all requests
VCRVCR::turnOn();

// Record requests and responses in cassette file 'example'
VCRVCR::insertCassette('example');

// Following request will be recorded once and replayed in future test runs
$result = file_get_contents('http://example.com');
$this->assertNotEmpty($result);

// To stop recording requests, eject the cassette
VCRVCR::eject();

// Turn off VCR to stop intercepting requests
VCRVCR::turnOff();

OAuth 2.0 Server

This library allows you to easily configure an OAuth 2.0 server and set up all the authentication levels needed to protect your API. It is fully standards compliant and supports all the grants defined by OAuth protocol. The Laravel Passport module is built on top of the OAuth 2.0 Server.

// Setup the authorization server
$server = new LeagueOAuth2ServerAuthorizationServer(
    $clientRepository,
    $accessTokenRepository,
    $scopeRepository,
    $privateKey,
    $publicKey
);

// Enable the a grant on the server
$server->enableGrantType(
    new LeagueOAuth2ServerGrantClientCredentialsGrant(),
    new DateInterval('PT1H') // access tokens will expire after 1 hour
);

Imagine

An image manipulation library that tries to bring together all low level PHP image processing libraries under the same object-oriented API. This allows Imagine to be used for a wide variety of tasks such as drawing, resizing, cropping, filters, effects, metadata editing, and others.

$palette = new ImagineImagePaletteRGB();

$image = $imagine->create(new Box(400, 300), $palette->color('#000'));

$image->draw()
    ->ellipse(new Point(200, 150), new Box(300, 225), $image->palette()->color('fff'));

$image->save('/path/to/ellipse.png');

MINI

Extremely simple and easy to understand skeleton PHP application, providing only the most essential features every project needs. It does not strive to be a do-it-all framework like Laravel, but due to it’s simplicity MINI can be used for getting smaller apps up and running in no time.

// Working with the model
$songs = $this->model->getAllSongs();
$amount_of_songs = $this->model->getAmountOfSongs();

// Loading views
require APP . 'views/_templates/header.php';
require APP . 'views/songs/index.php';
require APP . 'views/_templates/footer.php';

AWS SDK

The official PHP library for working with Amazon Web Services. The SDK makes it easy to connect AWS with any PHP project and access all the various available services. There is also a useful Laravel wrapper which can be found here.

// Instantiate an Amazon S3 client.
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-west-2'
]);

$s3->putObject([
    'Bucket' => 'my-bucket',
    'Key'    => 'my-object',
    'Body'   => fopen('/path/to/file', 'r'),
    'ACL'    => 'public-read',
]);

Purl

Lightweight PHP library for working with URLs. With Purl you can compose complex paths attribute by attribute, extract data from URLs, manipulate queries, recognize URLs in strings, and much more.

$url = PurlUrl::parse('http://jwage.com')
    ->set('scheme', 'https')
    ->set('port', '443')
    ->set('user', 'jwage')
    ->set('pass', 'password')
    ->set('path', 'about/me')
    ->set('query', 'param1=value1&param2=value2');

echo $url->getUrl(); // https://jwage:password@jwage.com:443/about/me?param1=value1&param2=value2
echo $url->publicSuffix; // com
echo $url->registerableDomain; // jwage.com

Daux.io

Documentation generator that uses a simple folder structure and Markdown files to create responsive documentation websites. Daux.io has automatic syntax highlighting, 4 theming options, Bootstrap HTML for easy customization, navigation with readable URLs, and many other goodies.

// Example configuration
{
    "title": "DAUX.IO",
    "tagline": "The Easiest Way To Document Your Project",
    "author": "Justin Walsh",
    "image": "app.png",
    "html": {
        "theme": "daux-blue",
        "breadcrumbs": true,
        "repo": "justinwalsh/daux.io",
        "edit_on_github": "justinwalsh/daux.io/blob/master/docs",
        "twitter": ["justin_walsh", "todaymade"],
        "google_analytics": "UA-12653604-10",
        "links": {
            "Download": "https://github.com/justinwalsh/daux.io/archive/master.zip",
            "GitHub Repo": "https://github.com/justinwalsh/daux.io",
            "Made by Todaymade": "http://todaymade.com"
        }
    }
}

Dompdf

Dompdf is a PDF generator that takes regular HTML markup and converts it to .pdf files. It understands most CSS rules, which can be fed in-line or via an external stylesheet.

// reference the Dompdf namespace
use DompdfDompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

Instaphp

Non-official library for accessing the Instagram API. It provides developers with an easy way to authenticate their app and get access to various Instagram data endpoints including images, users, likes, comments, and tags.

$api = new InstaphpInstaphp([
    'client_id' => 'your client id',
    'client_secret' => 'your client secret',
    'redirect_uri' => 'http://somehost.foo/callback.php',
    'scope' => 'comments+likes'
]);

$popular = $api->Media->Popular(['count' => 10]);

if (empty($popular->error)) {
    foreach ($popular->data as $item) {
        printf('<img src="%s">', $item['images']['low_resolution']['url']);
    }
}

Latitude

Zero-dependencies library for building SQL queries using chainable methods. It supports most query types and works well with MySQL, Postgres, SQL Server, and other databases. There are also built-in escaping helpers for protecting against SQL injection.

$select = SelectQuery::make(
        'id',
        'username'
    )
    ->from('users');

echo $select->sql();
// SELECT id, username FROM users

Source:: Tutorialzine.com

Basic OOP(object oriented programing) concept in C# (CSharp).

By S Sharif Object Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic. Object Oriented Programing (OOP CSharp) allows decomposition of a problem into a number of entities…

The post Basic OOP(object oriented programing) concept in C# (CSharp). appeared first on Technical Diary.

Visit www.technicaldiary.com to read, full article.

Source:: TECHNICALDIARY

C# 7 Features and High level overview. Tuples, Pattern matching, Literal improvements, Ref return types etc…

By S Sharif C# 7 Features: C# 7.0 has number of new features and it’s focus on data consumption, code simplification and performance improvement. In C# 7.0 biggest features are tuples (which makes it easy to have multiple results), and…

The post C# 7 Features and High level overview. Tuples, Pattern matching, Literal improvements, Ref return types etc… appeared first on Technical Diary.

Visit www.technicaldiary.com to read, full article.

Source:: TECHNICALDIARY