Laravel – PHP web framework Vs Rails, Installation

Laravel is a php web framework which following the model–view–controller (MVC) architectural pattern. It is gaining more and more popularity nowadays.

It is almost followed Ruby on Rails framework pattern, not only for MVC structure but also for the pattern that Rails adopt for doing various tasks. It uses composer that installs the software snippets you needed to achieve a particular task as Rails does it with bundler to pick gems.

The drawback of Laravel is it cannot achieve the power of Ruby like metaprogramming through php. Because of this I need to write so many code in Laravel that feels irritating if you want to write less code without the same repetitive patterns.

Get and install composer

Goto (https://getcomposer.org/) Click download.

Run the following:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

This will install ‘composer.phar ‘ in the current directory.

Move that to bin folder to get it globally available as a command and rename it to composer

$ mv composer.phar /usr/local/bin/composer

Open new tab and Type

$ composer

Install Lareval

Using composer

$ composer create-project --prefer-dist laravel/laravel blog "5.4.*"

From laravel/laravel github repo OR via larval installer

$ laravel new blog
-bash: laravel: command not found

Install it:

$ composer global require "laravel/installer"

this makes it globally accessible

Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system.

Open ~/.bash_profile OR ~/.bashrc in Mac

and add the following line:

export PATH="$PATH:$HOME/.composer/vendor/bin"

save and exit

Open New tab type:

$ laravel
Laravel Installer 1.4.1
Usage:
  command [options] [arguments]

Check Laravel version:

$ php artisan --version
Laravel Framework 5.4.27

You are ready to go!

Advertisements

Launch sublime text 3 from command line in mac

An executable file to open the sublime editor is already contained in the Sublime directory itself. By default this is not added to your $PATH, in your command-line interpreter.

So add that executable file to one of the directory that included in $PATH.

$ ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/sublime

Here ‘/usr/local/bin/’ is present in my $PATH

Then take sublime as following:

$ sublime ~/projects/my-app

Here ‘~/projects/my-app’ is your application path.

Create bootable usb drive of OSX from Mac OS

You can use mac’s createinstallmedia command. The format to create a bootable USB is given below.

$ sudo /Applications/Install\ macOS\ Sierra.app/Contents/Resources/createinstallmedia --volume |YOUR-USB-DRIVE-PATH-HERE| --applicationpath |DOT-APP-FILE-MACOS|

In My system the command will be as follows:

$ sudo /Applications/Install\ macOS\ Sierra.app/Contents/Resources/createinstallmedia --volume /Volumes/ABHI\'S/ --applicationpath /Applications/Install\ macOS\ Sierra.app/

You can easily find the corresponding software path in your system, if you have a different OS that mentioned above.

For more details, visit:
https://support.apple.com/en-us/HT201372

How to send Basic Authentication (BA) credentials in ruby on rails

HTTP Basic authentication is a simple authentication scheme in which user authentication is done by a username and password eliminating the needs of cookies, sessions and login pages. It is base64 encoded.

Rails provides a method for this type of authentication: authenticate_with_http_basic

This method can be used as follows:

authenticate_with_http_basic do |username, password|
  ——
end

Inside the block you can access the username and password.

But how to send a request with basic auth in rails ?

This is really tricky and I didn’t find any documentation for this. Here I am describing how to send a request with basic auth.

1. Use Faraday library (Faraday is an HTTP client lib)
https://github.com/lostisland/faraday

Create a connection:

connection = Faraday.new(:url => HOST) do |faraday|
      faraday.request  :url_encoded             # form-encode POST params
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
      faraday.basic_auth(USERNAME, PASSWORD)
end

parameters = params[‘user’].permit!.to_h

response = connection.get do |req|
      req.url(params[:url])
      req.headers['Content-Type'] = 'application/json'
      req.params.merge!(parameters)
end

response = connection.post do |req|
        req.url(params[:url])
        req.headers['Content-Type'] = 'application/json'
        req.body = parameters
end

render json: response.body

Here,

HOST = 'http://lvh.me:3002'
USERNAME = 'EdcddzrbmET55016'
PASSWORD = 'UXBJnS309S49st3rHqmH5934'
params['url'] = '/users/profile'

We can use Faraday’s (‘faraday.basic_auth’) basic auth method to reach out our solution.

If you are getting any error like follows in post request

NoMethodError (undefined method `bytesize' for {}:ActiveSupport::HashWithIndifferentAccess):

Don’t forget to convert the ruby hash ‘parameters’ to json by calling ‘to_json’ upon it.

        req.body = parameters.to_json 

In Other way you can use something like this to generate the basic auth header

request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(USERNAME, PASSWORD)

How to use Ruby Rest Client:

require 'rest_client'

headers = {
  :authorization => 'Basic FytxhZGKpbjpvcGVuIHNlc2FtHUHU'
}

response = RestClient.get 'https://yourdomain.com/api/users.json?activityId=02ddf868-6484-440f-8c39-c7d4fb4e7b33', headers
puts response

Install latest PHP version on Mac using homebrew

Check php latest version here: http://php.net/downloads.php
=> Update your homebrew

$ brew update
$ brew upgrade

=> Install a centralized repository for PHP-related brews: homebrew-php
https://github.com/Homebrew/homebrew-php

Requirements
* Homebrew
* Yosemite, El Capitan, and Sierra. Untested everywhere else.

Run the following in your command-line:

$ brew tap homebrew/homebrew-php

$ brew search php

will show you all php formula

We will Install php 7.1, because php 7.1.8 is the latest stable version till now (Aug 2017)

$ brew install php71

Check php version installed

$ php --version
PHP 7.1.8 (cli) (built: Aug  7 2017 15:02:19) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies

You are done.

Rbenv: Start with new ruby and rails versions

Check for the new ruby and rails versions
https://www.ruby-lang.org/en/downloads/
https://rubygems.org/gems/rails/versions

Suppose we are going to install Ruby – 2.4.1 & Rails – 5.1.3

Get rbenv into action
If you are not installed rbenv, you can install it from here:
https://github.com/rbenv/rbenv
After the installation make sure that, your $PATH has included rbenv/shims path. Else rbenv will not work.

1. $ rbenv install --list # Gets the list of ruby versions available

$ rbenv install 2.4.1

ruby-build: definition not found: 2.4.1

The following versions contain `2.4.1' in the name:
  rbx-2.4.1

See all available versions with `rbenv install --list'.

If the version you need is missing, try upgrading ruby-build:

  brew update && brew upgrade ruby-build

Oops..!

rbenv cannot find the version: 2.4.1

Upgrade ruby-build

Mac OSX:

$ brew upgrade ruby-build --HEAD

Now install ruby 2.4.1

$ rbenv install 2.4.1

Create a new gemset:

Rbenv gemset is a separate script and not coming with rbenv. If you are not installed this, you can install it from here:
https://github.com/jf/rbenv-gemset

$ rbenv gemset create 2.4.1 demo-app
That set up a directory for you in ~/.rbenv/versions/2.4.1/gemsets/demo-app

Set the ruby version to the newest

$ rbenv local 2.4.1

$ rbenv version
=> 2.4.1

    Activate New Gemset


For activating a gemset we need to create a .rbenv-gemsets file in the current directory.

$ touch .rbenv-gemsets
$ echo demo-app > .rbenv-gemsets

Check active gemset:

$ rbenv gemset active

Install Rails 5.1.3

$ gem install rails -v '5.1.3'
$ gem install --no-rdoc --no-ri rails -v '5.1.3' # skips the documentation

Later we can delete this .rbenv-gemsets file and add a new file named ‘.ruby-gemset’ in the rails project directory. I cannot find any other option for doing this. If anyone know more about this, please give a comment. I appreciate that.

Create a New Rails app

$ rails new demo-app

$ rm .rbenv-gemsets

$ cd demo-app
$ touch .ruby-gemset
$ echo demo-app > .ruby-gemset
$ touch .ruby-version
$ echo 2.4.1 > .ruby-version
$ rails s
=> Booting Puma
=> Rails 5.1.3 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.9.1 (ruby 2.4.1-p111), codename: Private Caller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

Goto http://localhost:3000/

rails-5-new.png

Done! Lets go…