How to write CanCanCan Ability for user to read only their data?

How do you restrict user access so a user can only read their own record?

How do you restrict user access so a user can only read their own record?

I've tried:

def initialize(user)
  can :read, User, :id => user.id

and this:

def initialize(user)
  can :read, user

but I can still access every user in index and show. I have authorize_resource in the UsersController.

Relevant documentation for reference:https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities

Build a CRUD Web App with Ruby on Rails

Build a CRUD Web App with Ruby on Rails

If you are fairly new to Ruby on Rails (or forgot how to use it) and need a quick guide to creating a CRUD (create, read, update, destroy) web application, then you’ve come to the right place!

If you are fairly new to Ruby on Rails (or forgot how to use it) and need a quick guide to creating a CRUD (create, read, update, destroy) web application, then you’ve come to the right place!

Below I have written some simple steps to creating a very simple application, linked to some documentation or a tutorial for each step, and included an example of what you might write for each step.

Here’s a nice, simple tutorial that gives some more context and explanation and walks you through these steps. This guide is also fairly easy to follow, much longer, and more detailed.

  1. Create a new app
rails new pets-app

  1. Launch a server and go to http://localhost:3000 in your browser to view your app
rails s

  1. Create models
rails g model owner first_name last_name age:integer email
rails g model pet name species owner_id:integer owner:belongs_to

  1. Set up associations
class Owner < ApplicationRecord
  has_many :pets
end

  1. Add validations
class Owner < ApplicationRecord
  has_many :pets
  validates :name, presence: true
end

  1. Run migrations
rails db:migrate

  1. Check your schema by looking at the db/schema.rb file

  2. Seed your database

Owner.create!(first_name:"Dan", last_name:"Weirdo", age: 18, email:"[email protected]")
Pet.create!(name:"Snowball", species:"dog", owner_id:1)

  1. Test associations
Owner.first.pets
Pet.first.owner

  1. Test validations
owner = Owner.new(first_name: "")
owner.valid?
owner.errors.messages

  1. Create controllers and views
rails g controller owners index show new create edit update destroy
rails g controller pets index show new create edit update destroy

  1. Create routes using resources or manual routes
resources :pets
resources :owners

  1. Make sure your routes are working correctly by running your server

(rails s) and looking at each path that you created (i.e. /pets)

  1. Add/edit controller actions

Hint: scroll to the bottom for an example of standard controller actions

  1. Add/edit view files

Hint: “find on page” “new.html”, “index.html”, etc. to see examples

Another hint: the form_for helper

That’s it! Make sure you test your code as you go, and commit often.

Why you should learn the Rust programming language

Why you should learn the Rust programming language

Rust has many features that make it useful, but developers and their needs differ. I cover five of the key concepts that make Rust worth learning

Discover the history, key concepts, and tools for using Rust

A recent Stack Overflow survey found that almost 80% of respondents loved using or wanted to develop with the Rust language. That’s an incredible number! So, what’s so good about Rust? This article explores the high points of this C-like language and illustrates why it should be next on your list of languages to learn.

Rust and its genealogy

First, let’s start with a quick history lesson. Rust is a new language relative to its predecessors (most importantly C, which preceded it by 38 years), but its genealogy creates its multiparadigm approach. Rust is considered a C-like language, but the other features it includes create advantages over its predecessors (see Figure 1).

First, Rust is heavily influenced by Cyclone (a safe dialect of C and an imperative language), with some aspects of object-oriented features from C++. But, it also includes functional features from languages like Haskell and OCaml. The result is a C-like language that supports multiparadigm programming (imperative, functional, and object oriented).

Figure 1. Rust and its family tree

Key concepts in Rust

Rust has many features that make it useful, but developers and their needs differ. I cover five of the key concepts that make Rust worth learning and show these ideas in Rust source.

First, to get a feel for the code, let’s look at the canonical “Hello World” program that simply emits that message to the user (see Listing 1).

Listing 1. “Hello World” in Rust
fn main()
{
   println!( "Hello World.");
}

This simple program, similar to C, defines a main function that is the designated entry point for the program (and every program has one). The function is defined with the fnkeyword followed by an optional set of parameters within parentheses (()). The curly braces ({}) delineate the function; this function consists of a call to the println! macro, which emits formatted text to the console (stdout), as defined by the string parameter.

Rust includes a variety of features that make it interesting and worth the investment to learn. You’ll find concepts like modules for reusability, memory safety and guarantees (safe vs. unsafe operations), unrecoverable and recoverable error handling features, support for concurrency, and complex data types (called collections).

Reusable code via modules

Rust allows you to organize code in a way that fosters its reuse. You achieve this organization by using modules, which contain functions, structures, and even other modules that you can make public (that is, expose to users of the module) or private (that is, use only within the module and not by the module users — at least not directly). The module organizes code as a package that others can use.

You use three keywords to create modules, use modules, and modify the visibility of elements in modules.

  • The mod keyword creates a new module
  • The use keyword lets you use the module (expose the definitions into scope to use them)
  • The pub keyword makes elements of the module public (otherwise, they’re private).

Listing 2 provides a simple example. It starts by creating a new module called bits that contains three functions. The first function, called pos, is a private function that takes a u32 argument and returns a u32 (as indicated by the -> arrow), which is a 1 value shifted left bit times. Note that a return keyword isn’t needed here. This value is called by two public functions (note the pub keyword): decimal and hex. These functions call the private pos function and print the value of the bit position in decimal or hexadecimal format (note the use of  to indicate hexadecimal format). Finally, it declares a main function that calls the bits module’s two public functions, with the output shown at the end of Listing 2 as comments.

Listing 2. Simple module example in Rust
mod bits {
fn pos(bit: u32) ‑> u32 {
1 << bit
}

pub fn decimal(bit: u32) {
println!("Bits decimal {}", pos(bit));
}

pub fn hex(bit: u32) {
println!("Bits decimal 0x{:x}", pos(bit));
}
}

Modules enable you to collect functionality in public or private ways, but you can also associate methods to objects by using the impl keyword.

Safety checks for cleaner code

The Rust compiler enforces memory safety guarantees and other checking that make the programming language safe (unlike C, which can be unsafe). So, in Rust, you’ll never have to worry about dangling pointers or using an object after it has been freed. These things are part of the core Rust language. But, in fields such as embedded development, it’s important to do things like place a structure at an address that represents a set of hardware registers.

Rust includes an unsafe keyword with which you can disable checks that would typically result in a compilation error. As shown in Listing 3, the unsafe keyword enables you to declare an unsafe block. In this example, I declare an unmutable variable x, and then a pointer to that variable called raw. Then, to de-reference raw (which in this case would print 1 to the console), I use the unsafe keyword to permit this operation, which would otherwise be flagged at compilation.

Listing 3. Unsafe operations in Rust
fn main() {
let a = 1;
let rawp = &a as const i32;

unsafe {
println!("rawp is {}", rawp);
}
}

You can apply the unsafe keyword to functions as well as blocks of code within a Rust function. The keyword is most common in writing bindings to non-Rust functions. This feature makes Rust useful for things like operating system development or embedded (bare-metal) programming.

Better error handling

Errors happen, regardless of the programming language you use. In Rust, errors fall into two camps: unrecoverable errors (the bad kind) and recoverable errors (the not-so-bad kind).

Unrecoverable errors

The Rust panic! function is similar to C‘s assert macro. It generates output to help the user debug a problem (as well as stopping execution before more catastrophic events occur). The panic! function is shown in Listing 4, with its executable output in comments.

Listing 04. Handling unrecoverable errors in Rust with panic!

fn main() {
panic!("Bad things happening.");
}

// thread 'main' panicked at 'Bad things happening.', panic.rs:2:4
// note: Run with RUST_BACKTRACE=1 for a backtrace.

From the output, you can see that the Rust runtime indicates exactly where the issue occurred (line 2) and emitted the provided message (which could emit more descriptive information). As indicated in the output message, you could generate a stack backtrace by running with a special environment variable called RUST_BACKTRACE. You can also invoke panic! internally based on detectable errors (such as accessing an invalid index of a vector).

Recoverable errors

Handling recoverable errors is a standard part of programming, and Rust includes a nice feature for error checking (see Listing 5). Take a look at this feature in the context of a file operation. The File::open function returns a type of Result<T, E>, where T and Erepresent generic type parameters (in this context, they represent std::fs::File and std::io::Error). So, when you call File::open and no error has occurred (E is Ok), T would represent the return type (std::fs::File). If an error occurred, E would represent the type of error that occurred (using the type std::io::Error). (Note that my file variable fuses an underscore [] to omit the unused variable warning that the compiler generated.)

I then use a special feature in Rust called match, which is similar to the switch statement in C but more powerful. In this context, I match _f against the possible error values (Okand Err). For Ok, I return the file for assignment; for Err, I use panic!.

Listing 5. Handling recoverable errors in Rust with Result<t, e>

use std::fs::File;

fn main() {
let _f = File::open("file.txt");

let _f = match _f {
Ok(file) => file,
Err(why) => panic!("Error opening the file {:?}", why),
};
}

// thread 'main' panicked at 'Error opening the file Error { repr: Os
// { code: 2, message: "No such file or directory" } }', recover.rs:8:23
// note: Run with RUST_BACKTRACE=1 for a backtrace.

Recoverable errors are simplified within Rust when you use the Result enum; they’re further simplified through the use of match. Note also in this example the lack of a File::close operation: The file is automatically closed when the scope of _f ends.

Support for concurrency and threads

Concurrency commonly comes with issues (data races and deadlocks, to name two). Rust provides the means to spawn threads by using the native operating system but also attempts to mitigate the negative effects of threading. Rust includes message passing to allow threads to communicate with one another (via send and recv as well as locking through mutexes). Rust also provides the ability to permit a thread to borrow a value, which gives it ownership and effectively transitions the scope of the value (and its ownership) to a new thread. Thus, Rust provides memory safety along with concurrency without data races.

Consider a simple example of threading within Rust that introduces some new elements (vector operations) and brings back some previously discussed concepts (pattern matching). In Listing 6, I begin by importing the thread and Duration namespaces into my program. I then declare a new function called my_thread, which represents the thread that I’ll create later. In this thread, I simply emit the thread’s identifier, and then sleep for a short time to permit the scheduler to allow another thread to run.

My main function is the heart of this example. I begin by creating an empty mutable vector that I can use to store values of the same type. I then create 10 threads by using the spawn function and push the resulting join handle into the vector (more on this later). This spawn example is detached from the current thread, which allows the thread to live after the parent thread has exited. After emitting a short message from the parent thread, I finally iterate the vector of JoinHandle types and wait for each child thread to exit. For each JoinHandle in the vector, I call the join function, which waits for that thread to exit before continuing. If the join function returns an error, I’ll expose that error through the match call.

Listing 6. Threads in Rust

use std::thread;
use std::time::Duration;

fn mythread() {
println!("Thread {:?} is running", std::thread::current().id());
thread::sleep(Duration::from_millis(1));
}

fn main() {
let mut v = vec![];

for _i in 1..10 {
v.push( thread::spawn(|| { my_thread(); } ) );
}

println!("main() waiting.");

for child in v {
match child.join() {
Ok() => (),
Err(why) => println!("Join failure {:?}", why),
};
}
}

On execution, I see the output provided in Listing 7. Note here that the main thread continued to execute until the join process had begun. The threads then executed and exited at different times, identifying the asynchronous nature of threads.

Listing 7. Thread output from the example code in Listing 6

main() waiting.
Thread ThreadId(7) is running
Thread ThreadId(9) is running
Thread ThreadId(8) is running
Thread ThreadId(6) is running
Thread ThreadId(5) is running
Thread ThreadId(4) is running
Thread ThreadId(3) is running
Thread ThreadId(2) is running
Thread ThreadId(1) is running

Support for complex data types (collections)

The Rust standard library includes several popular and useful data structures that you can use in your development, including four types of data structures: sequences, maps, sets, and a miscellaneous type.

For sequences, you can use the vector type (Vec), which I used in the threading example. This type provides a dynamically resizeable array and is useful for collecting data for later processing. The VecDeque structure is similar to Vec, but you can insert it at both ends of the sequence. The LinkedList structure is similar to Vec, as well, but with it, you can split and append lists.

For maps, you have the HashMap and BTreeMap structures. You use the HashMap structure to create key-value pairs, and you can reference elements by their key (to retrieve the value). The BTreeMap is similar to the HashMap, but it can sort the keys, and you can easily iterate all the entries.

For sets, you have the HashSet and BTreeSet structures (which you’ll note follow the maps structures). These structures are useful when you don’t have values (just keys) and you easily recall the keys that have been inserted.

Finally, the miscellaneous structure is currently the BinaryHeap. This structure implements a priority queue with a binary heap.

Installing Rust and its tools

One of the simplest ways to install Rust is by using curl through the installation script. Simply execute the following string from the Linux® command line:

curl -sSf https://static.rust-lang.org/rustup.sh | sh

This string transfers the rustup shell script from rust-lang.org, and then passes the script to the shell for execution. When complete, you can execute rustc -v to show the version of Rust you installed. With Rust installed, you can maintain it by using the rustuputility, which you can also use to update your Rust installation.

The Rust compiler is called rustc. In the examples shown here, the build process is simply defined as:

rustc threads.rs

…where the rust compiler produces a native executable file called threads. You can symbolically debug Rust programs by using either rust-lldb or rust-gdb.

You’ve probably noticed that the Rust programs I’ve demonstrated here have a unique style. You can learn this style through the automatic Rust source formatting by using the rustfmt utility. This utility, executed with a source file name, will automatically format your source in a consistent, standardized style.

Finally, although Rust is quite strict in what it accepts for source, you can use the rust-clippy program to dive further in to your source to identify elements of bad practice. Think of rust-clippy as the C lint utility.

Windows considerations

On Windows, Rust additionally requires the C++ build tools for Visual Studio 2013 or later. The easiest way to acquire the build tools is by installing Microsoft Visual C++ Build Tools 2017 which provides just the Visual C++ build tools. Alternately, you can install Visual Studio 2017, Visual Studio 2015, or Visual Studio 2013 and during the install, select C++ tools.

For further information about configuring Rust on Windows, see the Windows-specific rustup documentation.

Going further

In mid-February 2018, the Rust team released version 1.24. This version includes incremental compilation, automatic source formatting with rustfmt, new optimizations, and library stabilizations. You can learn more about Rust and its evolution at the Rust blog and download Rust from the Rust Language website. There, you can read about the many other features Rust offers, including pattern matching, iterators, closures, and smart pointers.

Originally published on https://developer.ibm.com

Top 5 Programming Languages For Jobs and Future

Top 5 Programming Languages For Jobs and Future

Many programming languages — confused about what to choose or pursue as a job. In this article, every programming language is briefly described which make easy for you to choose and learn according to your interest.

Originally published by John Walter at https://dzone.com

Sometimes it is difficult to find the best out of the rest. Here are the top five programming languages and their job rates and future scope.

Before starting with languages, let’s brief that what is programming language is?

Introduction to Programming Language 

The programming language is a language that contains a set of instructions that produce various kinds of outputs. It is used in computer programming to execute algorithms.

Thousands of different programming languages built and many more created every year but only a few implemented in the market or used by developers.

Only those programming languages, that are easy to use and understand. The classification of a programming language usually divided into two ingredients — syntax (form) and semantics (meaning).

Syntax

  • It is the surface form of a programming language.
  • Most of the programming languages are purely textual, so they use sequences of text including words, numbers, and punctuation.
  • The syntax of a language expresses the possible compounds/combination of symbols.

Semantics

  • The meaning of programming languages.
  • There are two types of semantics- 
  • Static semantics — The static semantics defines restrictions on the structure of valid texts that are hard or impossible to express in standard syntactic formalisms. 
  • Dynamic semantics — The machine must be instructed to perform operations on the data.  
Top Programming Languages and Their Jobs and Future Scopes

Source: Codersera

Several new programming languages are coming up that revised for different categories of developers (beginners, average, and experts). As well as for different use cases (web application, mobile applications, game development, distributed system, etc).

The most essential skill to learn in today’s scenario is how to write a computer program. The programming and developer communities are emerging at a rate faster than ever before.

Python

It is a general-purpose programming language, which is used to build easy and tools and libraries. For backend web development, artificial intelligence, data analysis, and scientific computing- python is a great language.

There are many developers who use python and find it simple and easy to learning. Therefore, they have used python to build productivity tools, games, and desktop applications. 

Today, Python has multiple implementations including Jython, scripted in Java language for Java Virtual MachineIronPython has written in C# for the Common Language Infrastructure, and PyPy version written in RPython and translated into C.

While these implementations work in the native language they are written in, they are also capable of interacting with other languages through the use of modules. Most of these modules work on the community development model and are open-source and free.

Advantages/Benefits of Python

The various application of the Python language is a combination of features which give this language advantages.

  • Supportive Libraries — Python provides a large standard library, which includes areas like internet protocols, string operations, web services tools, and operating system interfaces.
  • Presence of Third Party Modules — The Python Package Index (PyPI) contains numerous third-party modules that make Python capable of interacting with most of the other languages and platforms.
  • Productivity and Speed — Python has a clean object-oriented design, which provides enhanced process control capabilities and possesses strong integration as well as text processing capabilities.
  • Open Source and Community Development — Python language is developed under an OSI-approved open source license, which makes it free to use and distribute, including for commercial purposes.
  • Learning Ease and Support Available — Python gives excellent readability and uncluttered easy-to-learn syntax which helps beginners to utilize this programming language. The code style guidelines, PEP 8, provides a set of rules which help to format the code.
  • User-friendly Data Structures — Python has built-in list and dictionary data structures, which can be used to create fast runtime data structures. Secondly, it also provides the option of high-level data typing which decreases the length of the support code that is needed.

Careers With Python

  • With many different programming languages available, Python has tremendously outraced the other languages.
  • Career opportunities associated with Python have also grown significantly as its popularity has increased by 40%.
  • Many IT businesses are looking for more candidates with experience and skills in Python programming languages.
  • This has illustrated the better career scope for the Python programmers in the near future.

Top Companies using Python Programming Language

Python has been voted for the most favourite programming language. It is assuredly beating other programming languages. It has been used for developing almost every kind of applications whether it is web applications or game applications.

Future of Python

[ImportantRecently, on 2nd July 2019, Python 3.6.9 offers drastic improvement, among other new features. Python 3.7.4 is the current version of Python which is released on July 8, 2019.

JavaScript

JS is the high-level, interpreted scripting language which follows the ECMAScript specification. It is the multi-paradigm, supporting object-oriented, dynamic, imperative, declarative and a prototype-based language.

Even it’s used in many non-browser environments. Javascript is an easy and the language that is used to design or program the webpages. Also, for controlling webpage behavior.

In Javascript, the basic syntax, intentionally related to Java and c++ languages to reduce the number of new concepts required to learn this language.

But “Javascript has not interpreted java”. The language constructs are such as:

  • "If" statements
  • "For" and "While" loops
  • "Switch, Catch" blocks function

JS is the dynamic capabilities that include runtime object construction, function variables, dynamic script creation, variable parameter lists, object introspection, and source code recovery. the common application for Javascript is the web server-side scripting language.

A Javascript web server would host an object that represents HTTP request and response objects for the Javascript program to generate dynamic web pages. The most popular example of Javascript is Node.js.

There are some databases like MongoDB and CouchDB which use Javascript as their programming language.

Different features of Javascript

Careers With JavaScript

There are so many options for freshers or experienced people:

  • Front-End web developer — This job focussed on HTML, CSS, JavaScript and light backend.
  • Web Application developer — Creating web-based software applications including interactive online forms, shopping carts, word processing, Email software, and file conversions using Javascript.
  • Javascript developer — Designing and developing new front-end applications for various platforms.
  • UX/UI designer — Design the product features according to users or clients. And find innovative ways to resolve UX problems as well as collaborate with UI designers to execute attractive designs.
  • Full-stack developer — Design the architecture of the web application.
  • DevOps engineer — This job is a link between IT and Developers like testing servers, deploying, version control, build processes and server software.

Future of JavaScript

No doubt that there are various frameworks (Vue.js, jQuery, Angular.js, and React.js) that have their own established in the market which is constantly growing as well as some frameworks might fail in future and some continually grow.

Comparison of Javascript frameworks

Looking at the statistics and market position, it does not seem that react.js will leave its popularity in recent times as well as in the future.

The future, however, it will be a hybrid of everything available today. Where one framework, which is defined as the easiest to adopt by developers and proposes a complete solution, uses complementary techniques such as web components, web assembly, and AI, to create an end to end solution for developing applications.

Java

It is a general-purpose programming language that is class-based, and object-oriented. Java code can run anywhere or on all platforms that support Java without the need for recompilation. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM). The syntax of Java is similar to C and C++.

Java is one of the popular programming languages. it is a widely-used programming language that designed according to any distributed environment of the internet. As well as Java can be used for creating complete applications.

Java Is Popular Because

  • Data is secure
  • Easy to learn
  • Code robust
  • Applets give flexibility
  • Portability in a network
  • Object-oriented
  • Platform-independent

Three Main Platforms of Java

  • Java SE (Standard Edition)
  • Java EE (Enterprise Edition)
  • JavaME (Micro Edition)

[Important] The latest version is Java 12 which is released in March 2019.

Different features of Java; Source: Codersera

Careers With Java

There are many career options with Java:

  • Back-end developer — This career path is the one most in-demand and offers worldwide. As freelancer or remote developers or in-office, companies demand back-end developers for them and with a good salary package.
  • Big data developer — This is fastly growing career option as most of the companies are looking for leveraging large data sets for various business and marketing.
  • Android developer — An android programmer as a career is a really good option with java.
  • Embedded devises developer — Using Java, this is a niche path that also has growth opportunities for the developers.

Developers position using Java

In the above graph, you find three years of representation of developers' positions.

Java is the one outstanding Android versatile application that improving the market. The popularity of Java is high than other programming languages.

Future of Java

No doubt that java would have an amazing future, as it is a future-oriented programming language for years. Secondly, Java has brought many new concepts in which the most significant one is the security of applications and programs. So, in the upcoming years, business organizations find Java applications more secure.

Ruby on Rails

It is an interpreted, high-level, general-purpose programming. Ruby is used to collecting garbage, it is a dynamic type of language that supports multiple programming paradigms. Also, it includes procedural, object-oriented and functional programming.

Rails is a development tool that gives web developers a framework and a structure to write code. It simply helps to build websites and applications. ” Convention over configuration” is the key principle of Ruby.

Why Developers Go With Ruby on Rails?

  • Ruby is faster than other frameworks and languages.
  • Same coding structure which makes coding easy for the developers.
  • Good for rapid application development (RAD) as well as easy to accommodate changes.
  • It developed a strong focus on testing.
  • Also, it has open-source libraries.

Amazing features of Ruby

Careers With Ruby

As now ruby on rail becomes the popular programming language. Ruby on rails entry-level jobs is Junior programmer and co-developers. As well as the experienced person gets the good opportunity of high-position jobs like chief technology officer, project leader, and senior developers. With these amazing jobs, they get an annual salary which is starts at $100,000 to $154,000.

Three levels:

  • The entry-level Ruby on Rails developer jobs includes setting up rail environment, managing database, handling requests, basic HTML, JavaScript, and CSS knowledge and performing basic tasks related to the development of Ruby on Rails application.
  • The mid-level RoR developer job requires you to have knowledge about ActiveRecord Associations, Design patterns, and Object Orientation.
  • The senior-level jobs in Ruby on Rails require the developers to have skills such as understanding of Ruby Metaprogramming, database modeling, monitoring skills, planning, and estimation.

Future of Ruby on Rail

After watching the career scope of Ruby, it looks like Ruby has a huge and bright future because it is—

  • Ideal for a low budget
  • Community
  • Easy testing
  • Consistency

Companies using Ruby on Rail.

PHP

Hypertext Preprocessor (PHP) is a general-purpose programming language, which is designed for web development. PHP code is usually processed by a PHP interpreter as a module in the webserver secondly, the PHP code executed with a command-line interface (CLI). It is a scripting language that adopts to server-side web development. So, it can be used for client-side GUI and command-line scripting. Many web hosting providers support PHP for their clients. Also, PHP is free of cost.

The main use of PHP is that it acts like a filter, which takes input from text and converts it into output another stream. And it common output as HTML. PHP main focuses on the server-side scripting languages that provide dynamic content from a webserver to the client.

Some features of PHP.

Why Developers Choose PHP?

  • PHP supports database management system and other open-source.
  • It also supports MySQL, Oracle, Sybase, etc.
  • It is simple and easy to learn.
  • Runs on platforms such as Linux, Windows, etc.

Careers with PHP

Becoming a PHP developer can open several doors throughout your career. The first step up the ladder from this position is a senior web developer job.

In this role, your responsibilities encompass all aspects of creating websites and software, including the supervision of PHP. From the position of a senior web developer, you can go on to become an IT manager, development director, Chief Technology Officer, or a senior .NET developer. These are just a few options you can take depending on your other qualifications.

Future of PHP

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter




Geocoding using Mapbox, Rails 5 and NuxtJS/VueJS

<strong>Geocoding is the process of taking latitude and longitude to determine an address, or taking an address and producing latitude and longitude coordinates.</strong>

Geocoding is the process of taking latitude and longitude to determine an address, or taking an address and producing latitude and longitude coordinates.

There are numerous reasons an application needs to use a geocoder. For Now Serving, we use it during the sign up process, as well as making it easy to find nearby restaurants with a single click of ‘Find Me’.

Let’s get to coding!

Rails API

We’ll need to grab the mapbox-sdk and add it to the Gemfile.

_gem_ **'mapbox-sdk'**, **'~>2'**

Create a simple initializer to set the access token in your app (e.g config/initializers/mapbox.rb)

**_Mapbox_**.access_token = MAPBOX_ACCESS_TOKEN

Next, let’s add a couple routes:

_namespace_ **:address_search do** _get_ **'expand'**, **to**: **'expand'** _get_ **'parse'**, **to**: **'parse'
end**

And an address_search_controller.rb:

class AddressSearchController < ApplicationController
Take an addresss and return lat/lng

def expand
begin
@addresses = Mapbox::Geocoder.geocode_forward(address_params[:a]) unless address_params[:a].nil?
render template: 'address_search/result'
rescue StandardError
render json: { errors: ['Unable to perform forward geocoding'] }
end
end

Take lat/lng array and return a postal address

def parse
begin
@location = { latitude: address_params[:latitude].to_f, longitude: address_params[:longitude].to_f }
@addresses = Mapbox::Geocoder.geocode_reverse(@location)
render template: 'address_search/result'
rescue StandardError
render json: { errors: ['Unable to perform reverse geocoding'] }
end
end

private

def address_params
params.permit(:a, :latitude, :longitude)
end
end

The expand method takes the a query params and asks the geocoder service to return a latitude/longitude array. For getting an address from lat/lng we are expecting a hash like { latitude: 0, longitude: 0 }.

You may not want to render a template here but in my case I wanted to always return an array, so the best way to ensure that happened was rendering it with jbuilder one-liner:

json.array! @addresses

And a request spec:

RSpec.describe 'Address Search' do

it 'parses an address and returns latitude and longitude' do
get '/api/v1/address_search/expand', params: { a: '401 B St, San Diego CA' }
expect(response).to be_successful
end

it 'parses latitude and longitude and returns an address' do
get '/api/v1/address_search/parse', params: { longitude: 127.0, latitude: -43.64}
expect(response).to be_successful
end
end

Front End

We’re using the awesome NuxtJS framework for our UI. If you haven’t used it before, definitely give it a look. If you can’t use it, don’t worry; this code will work fine without Nuxt.

We use Vuex actions to call our back end, so we have a store for our Mapbox configuration.

export const actions = {
locate({ commit }, { longitude, latitude }) {
return this.$axios.get('/address_search/parse', { params: { longitude: longitude, latitude: latitude } })
},
coordinate({ commit }, params) {
return this.$axios.get('/address_search/expand', { params: { a: params } })
}
}

For presentation, we use vue-i18n, vue-notify, bootstrap-vue and vue-fontawesome.

<template>
<b-btn
v-b-tooltip.hover="true"
:data-state="state"
:variant="btnVariant"
:title="locationLabel"
type="button"
@click="findMe">
<font-awesome-icon v-if="state === 1" :icon="['far', 'spinner']" spin />
<font-awesome-icon v-else :icon="['far', 'location-arrow']" />
</b-btn>
</template>
<script>
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

export default {
components: {
FontAwesomeIcon
},
props: {
locationLabel: {
default: 'Find my current location',
type: String
}
},
data() {
return {
state: 0
}
},
computed: {
btnVariant() {
switch (this.state) {
case 0:
return 'outline-primary'
case 1:
return 'info'
case 2:
return 'success'
default:
return 'outline-primary'
}
}
},
methods: {
findMe() {
const vm = this
this.state = 1
if (!navigator.geolocation) {
vm.$notify({ text: vm.$t('geolocation.not_supported'), group: 'alerts' })
return
}

  function success(position) {
    const accuracy = position.coords.accuracy
    vm.$store.dispatch('mapbox/locate', {
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      accuracy: accuracy
    })
      .then((resp) =&gt; {
        vm.state = 2
        vm.$emit('result', { name: resp.data[0].features[0].place_name, center: resp.data[0].features[0].center })
      })
      .catch(() =&gt; {
        vm.state = 0
        vm.$notify({ text: vm.$t('geolocation.not_found'), type: 'warning', group: 'alerts' })
      })
  }

  function error() {
    vm.$notify({ text: vm.$t('geolocation.not_found'), group: 'alerts', type: 'warning' })
  }

  navigator.geolocation.getCurrentPosition(success, error)
}

}
}
</script>

There’s a lot going on here, so lets break it all down.

The location button has three states; default state, active state, and a success state. The computed property handles changing out the css classes for each state.

There is also a tooltip that displays on hover to explain that the browser will ask for permission to send location information to the back end.

The findMe method is called on click. In it we have two callbacks for success and error that the browser’s built in [getCurrentPosition](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition)needs to work correctly. When the browser provides the latitude and longitude to the success callback, we can send that to the back end using the Vuex action. Once the back end response comes, the component emits a result event containing the address name and coordinates. If permission is denied, we display an error notification. Also if the browser doesn’t support location services, we notify the user of that case.

Conclusion

Congrats you have a fully implemented API for forward and reverse geocoding solution!

Originally published by Todd Baur at https://itnext.io

Learn more

☞ The Complete Ruby on Rails Developer Course

☞ Testing Ruby with RSpec: The Complete Guide

☞ How to build Instagram using Ruby on Rails

☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

☞ Nuxt JS with Laravel - Build API driven SSR Vue JS Apps

What's New in Rails 6?

What's New in Rails 6?

As most Ruby on Rails fans might be aware, Rails 6 was released this April at RailsConf 2019 and brought a number of eagerly awaited features and changes. Here is a quick recap of the key Rails 6 features you are likely to be using moving forward

As most Ruby on Rails fans might be aware, Rails 6 was released this April at RailsConf 2019 and brought a number of eagerly awaited features and changes. Here is a quick recap of the key Rails 6 features you are likely to be using moving forward

For starters, remember that Rails 6 requires Ruby 2.5+ and upgraded databases. So, make sure you have a plan to upgrade your systems accordingly, in case you have not done so already.

Testing in Rails 6

As professional Ruby on Rails developers, we aim to ensure maximum coverage for our code. However, testing becomes a tedious activity when our test cases become “heavy” and we have to wait several minutes, or even hours, just to get the test cases executed.

Parallel Testing

Well, Rails 6 has an answer here. It has added a parallelize method to the ActiveSupport::TestCase which allows you to parallelize the test suite with forked processes.

So, what you need to do to parallelize the processes for your tests is add this to your test_helper.rb:

parallelize(workers: 2)

Alternatively, we can replace our previously used commands for running tests. For example, bin/rails test OR bin/rspec spec can now be replaced by PARALLEL_WORKERS=15 rails test OR PARALLEL_WORKERS=15 rspec spec.

Accordingly, you can change the commands for running the test suites on different CI platforms like Travis, Gitlab, CircleCI, and others.

There are also hooks when each process is created/destroyed, which can be used as follows:

class ActiveSupport::TestCase
  parallelize_setup do |worker|
    # setup databases
  end
  parallelize_teardown do |worker|
    # cleanup databases
  end
  parallelize(workers: :number_of_processors)
end

Note: If you’d like to learn more, you can check out Rails Guides for additional details.

Action Cable Testing

Since we were talking about efficient testing, let’s also understand how Action Cable, one of the most salient features of Rails 5, has improved. Now it is possible to test Action Cable at any level: connections, channels, and broadcasts.

Connection tests aim to check whether a connection’s identifiers get assigned properly or that any improper connection requests are rejected:

class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase
  test "connects with params" do
 
    connect params: { user_id: 42 }
    OR
    cookies.signed[:user_id] = "42"
    connect
 
    assert_equal connection.user_id, "42"
  end
  test "rejects connection without params" do
    assert_reject_connection { connect }
  end
end

Channel tests can be written to check whether users can subscribe to channels and the channel has a stream:

class ChatChannelTest < ActionCable::Channel::TestCase
  test "subscribes and stream for room" do
    # Simulate a subscription creation by calling `subscribe`
    subscribe room: "15"
    # You can access the Channel object via `subscription` in tests
    assert subscription.confirmed?
    assert_has_stream "chat_15"
  end
end

Broadcasting to channels can be tested like this:

# app/jobs/chat_relay_job.rb
class ChatRelayJob < ApplicationJob
  def perform_later(room, message)
    ChatChannel.broadcast_to room, text: message
  end
end
# test/jobs/chat_relay_job_test.rb
require 'test_helper'
class ChatRelayJobTest < ActiveJob::TestCase
  include ActionCable::TestHelper
  test "broadcast message to room" do
    room = rooms(:all)
    assert_broadcast_on(ChatChannel.broadcasting_for(room), text: "Hi!") do
     ChatRelayJob.perform_now(room, "Hi!")
    end
  end
end

Bulk Insert and Upsert

At some point, we all need to insert multiple records in one go and have found many workarounds when doing so. Well, Rails 6 comes with a new method out of the box—insert_all, similar to update_all.

It won’t fire any callbacks and will execute a single SQL query. There is an additional method upsert_all which allows you to use the upsert operation which is exposed by many modern databases like Postgres. So now you can reduce your insert queries and make your code more optimized. Also, say goodbye to previously used gems like activerecord-import.

A single INSERT SQL query is prepared by these methods, and a single SQL statement is sent to the database, without instantiating the model, or invoking Active Record callbacks and validations. It is also possible to define criteria when a primary key—unique indexes or unique constraints are violated with an option to either skip or run upsert queries.

Some examples are below:

result = Article.insert_all(
  [
    { id: 1,
      title: 'Handling 1M Requests Per Second',
      author: 'John',
      slug: '1m-req-per-second' },
    #...snip...
  ],
  returning: %w[ id title ],
  unique_by: :index_articles_on_title_and_author
)
 
 
result = Article.upsert_all(
  [
    { id: 1, title: 'Handling 1M Requests Per Second', author: 'John', slug: '1m-req-per-second' },
    { id: 1, .... }, # duplicate 'id' here
    { id: 2, .... },
    { id: 3, .... }, # duplicate 'title' and 'author' here
    { id: 4, .... },
    { id: 5, .... }, # duplicate 'slug' here
    { id: 6, .... }
  ]
)

The methods insert, insert! and upsert are wrappers around insert_all, insert_all! and upsert_all, respectively.

Switching Between Multiple Databases

One of the main features many big applications will appreciate is this one: Rails 6 has finally added support for multiple databases for your application, built in and ready to go, out of the box!

Of course, the design choice is still yours, whether you want to break your application into multiple microservices with each having a separate database, or take a monolithic route, or add several read replicas for your application.

However, having the ability to do it in such an easy manner has the potential to save a lot of time on the development front.

So, this is how your new database.yml file will look:

development:
  primary:
    database: my_primary_db
    user: root
  primary_replica:
    database: my_primary_db
    user: ro_user
    replica: true
  animals:
    database: my_animals_db
    user: root
  animals_replica
    database: my_animals_db
    user: ro_user
    replica: true

Here are interesting ways of specifying how to switch to different databases:

class AnimalsModel < ApplicationRecord
  self.abstract_class = true
 
  connects_to database: { writing: :animals_primary, reading: :animals_replica }
end
 
class Dog < AnimalsModel
  # connected to both the animals_primary db for writing and the animals_replica for reading
end

Here is the official GitHub page, which is nicely documented as well. Personally, I am looking forward to having database sharding capabilities in future Rails updates as well.

Action Mailbox

Another interesting React 6 feature is the addition of Action Mailbox, which adds the capability to route incoming emails to the controller like mailboxes for processing in Rails.

Action Mailbox features ingresses for Mailgun, Mandrill, Postmark, and SendGrid. You can also handle inbound emails directly via built-in Exim, Postfix, and Qmail ingresses. Now, you can probably imagine the potential benefits without going into more detail. It may be directly processing mails from a help desk to automating support tickets—Rails 6 allows customers to reply directly through email, and much, much more. The floor is open for you to explore this feature and come up with an approach that is ideal for your application.

Here is a small example to understand how to use Action Mailbox:

COMMENTS_REGEX = /^comment\+(.+)@example\.com/i
 
# app/mailboxes/application_mailbox.rb
class ApplicationMailbox < ActionMailbox::Base
  routing COMMENTS_REGEX => :comments
end
 
# app/mailboxes/comments_mailbox.rb
class CommentsMailbox < ApplicationMailbox
  def process
    user = User.find_by(email: mail.from)
    post_uuid = COMMENTS_REGEX.match(mail.to)[1]
   
    post = Post.find_by(uuid: post_uuid)
    post.comments.create(user: user, content: mail.body)
  end
end

Also, the new way of configuring emails is as follows (taking the example of Sendgrid):

# config/environments/production.rb
config.action_mailbox.ingress = :sendgrid

Use rails credentials:edit to add the password to your application’s encrypted credentials under action_mailbox.ingress_password, where Action Mailbox will automatically find it:

action_mailbox:
  ingress_password: …

Configure the SendGrid Inbound Parse to forward inbound emails to /rails/action_mailbox/sendgrid/inbound_emails with the username actionmailbox and the password you previously generated. If your application lives at <a href="https://example.com" target="_blank">https://example.com</a>, you would configure SendGrid with the following URL:

https://actionmailbox:[email protected]/rails/action_mailbox/sendgrid/i 

Zeitwerk

Zeitwerk is the new code loader for Ruby. Given a conventional file structure, Zeitwerk loads your project’s classes and modules on demand, meaning you don’t need to write require calls for your own files. To enable it in Rails 6, you can do the following:

config.autoloader = :zeitwerk

You can read more about Zeitwerk here.

Optimizer Hints

You are concerned that some of your queries are taking too long to execute? Well, now you have a way to define time-outs for your queries, too.

The following statement will raise an StatementTimeout exception if the query takes longer than normal to execute:

User.optimizer_hints("MAX_EXECUTION_TIME(5000)").all

It is supported by MySQL and you’ll have to explore if your database supports it.

Truncate Database

What about seeding data? The following statement will truncate all your database tables and you can then proceed to seeding your data:

rails db:truncate_all

No more deleting your databases to seed. You will probably agree this is an elegant and quick solution.

Action Text

Perhaps another notable feature for many applications that play with WYSIWYG editors is the addition of support for Trix editor natively into Rails 6 applications. This will certainly be a good upgrade/addition for many projects.

Most WYSIWYG HTML editors are enormous in scope—each browser’s implementation has its own set of bugs and quirks, and JavaScript developers are left to resolve the inconsistencies. Trix sidesteps these inconsistencies by treating contenteditable as an I/O device: When input makes its way to the editor, Trix converts that input into an editing operation on its internal document model, then re-renders that document back into the editor. This gives Trix complete control over what happens after every keystroke.

Installation:

rails action_text:install
 
# app/models/message.rb
class Message < ApplicationRecord
  has_rich_text :content
end

You can explore Action Text in further detail in the official documentation, here.

Security

No serious upgrade is complete without a few security enhancements. Rails 6 doesn’t disappoint on the security front, either. The first notable security upgrade is the addition of support for Host Authorization.

Host Authorization is a new middleware that guards against DNS rebinding attacks by explicitly permitting the hosts a request can be sent to. What this means is that you can define the hosts that can access your applications.

Another security upgrade is meant to thwart attacks that attempt to copy the signed/encrypted value of a cookie and use it as the value of another cookie. It does so by stashing the cookie name in the purpose field which is then signed/encrypted along with the cookie value. Then, on the server-side read, we verify the cookie names and discard any attacked cookies. Enable action_dispatch.use_cookies_with_metadata to use this feature, which writes cookies with the new purpose and expiry metadata embedded.

Webpack as the Default Bundler

As is the de facto standard with many modern JavaScript frameworks for front-end development, Rails 6 has added Webpack as the default JavaScript bundler through webpacker gem, replacing the Rails Asset pipeline. This is a relatively straightforward addition, and we won’t go into much detail. Suffice to say that Webpack will bring some relief to overworked front-end developers.

Preventing Race Conditions

Rails 6 has a new method which is used to prevent SELECT/INSERT race conditions in our code (I am sure many readers have had the misfortune of encountering race conditions as they scale their project). Here is the GitHub thread in case you need additional info.

The underlying table must have the relevant columns defined with unique constraints. While we avoid the race condition between SELECT → INSERT from #find_or_create_by, we actually have another race condition between INSERT → SELECT, which can be triggered if a DELETE between those two statements is run by another client. But, for most applications, that’s a condition we’re significantly less likely to hit.

Credentials in Rails 6

Since the days of Rails 5.2, credentials have been named a new “Rails way” to deal with sensitive information with a promise to get rid of infamous .env files once and for all. With credentials, encrypted keys for third-party services can be checked directly into the source control.

Until now, however, Rails used the same encrypted file for all environments, which made dealing with different keys in development and production a little tricky, especially when dealing with big projects and legacy code.

In Rails 6, this is finally solved with support for per-environment credentials. Again, further details can be explored on the official GitHub thread.