Arquivo da categoria: Javascript

Cangaceiro JavaScript – Uma aventura no sertão da programação

Nota do livro: 10.

Descrição: Como contratar, preparar, motivar e liderar profissionais de alto rendimento, sem ser especialista no assunto? Para responder a essa pergunta fundamental, o autor, baseado em mais de 30 anos de experiência em consultorias e treinamentos, preparou um manual prático para gestores que gostariam de obter excelentes resultados em sua atividade profissional, e mostra, de forma objetiva, como formar equipes compactas de altíssimo potencial. O livro está dividido em duas partes: Na Parte 1 – Autoconhecimento e análise, veremos que, para montar um time de grande qualidade, primeiro você precisa conhecer seu estilo de ser, em que estágio está seu negócio e como é o desempenho de sua equipe atual. Na parte 2 – Tomadas de decisão e estratégias, você receberá técnicas muito claras sobre como aproveitar o que seus colaboradores têm de melhor, como agregar novos profissionais e até como começar a montar um grupo vencedor do zero, se for necessário. Alguns assuntos abordados: – Teste: Qual é seu estilo de liderança? – Os principais perfis profissionais e o lugar certo para cada um deles. – Como avaliar seus subordinados. – Onde e como encontrar talentos gastando pouco. – Roteiro de perguntas para fazer uma entrevista de seleção eficaz. – Critérios práticos para demitir, promover, treinar ou dar condições especiais. – Como implantar a cultura da “dor de dono” em sua equipe. – A maneira correta de dar feedbacks. – Como atingir altos estágios de performance.”

Talvez nenhuma outra linguagem tenha conseguido invadir o coletivo imaginário dos desenvolvedores como JavaScript fez. Em sua história fabular em busca de identidade, foi a única que conseguiu se enraizar nos navegadores, tornando-se uma linguagem em que todo desenvolvedor precisa ter algum nível de conhecimento.

Neste livro completíssimo, adentre o sertão do JavaScript com o cangaceiro Flávio Almeida percorrendo os principais recursos das versões ES5, ES6, ES7 e ES8. Transite entre os paradigmas Orientado a Objetos e o Funcional e aplique padrões de projetos para sobreviver durante sua caminhada.

Transcenda seu conhecimento incluindo em seu arsenal de desenvolvedor IndexedDB, Babel e Webpack, tornando-se um Cangaceiro JavaScript!

how to add authentication header to $window.open

//Add authentication headers as params
var params = {
    access_token: 'An access_token',
    other_header: 'other_header'
};
 
//Add authentication headers in URL
var url = [url_generating_pdf, $.param(params)].join('?');
 
//Open window
window.open(url);

Style a text field in JasperReports

Yes, you can apply style for textField elements.

iReport using

The sample of report’s template:
[code type=xml]





















:” + $F{TASKS_SUBTASK} + “ \n “]]>



The quote from iReport Ultimate Guide about markup attribute:

This Markup attribute allows you to format the text using a specific markup language. This is extremely useful when you have to print some text that is pre-formatted, that is, in HTML or RTF. Simple HTML style tags (like for bold and for Italic) can be used in example to highlight a particular chunk of the text. The possible values are as follows:

  • None
    No processing on the text is performed, and the text is printed exactly like it is provided.
  • Styled
    This markup is capable to format the text using a set of HTML-like tags and it is pretty popular in the Java environments. It allows to set a specific font for chunks of text, color, background, style and so on. It’s often good enough to format the text programmatically.
  • HTML
    If you want to print some HTML text into your report, this is what you need, but it’s primary use is to format text, so don’t expect to be able to print tables or add images.
  • RTF
    Setting the markup to this value, the content will be interpreted as RTF code. RTF is a popular document format stored in pure text. The little piece of text saying “this is a text formatted in RTF” in Illustration 19 has been generated using the string:
    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}{\f1\fnil\fprq2\fcharset0 Swift;}} {*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20 This is a text \f1\fs52 formatted \f0\fs20 in RTF\par }
    The string is actually an RTF file created using a simple word processor.
  • Report font
    This is the name of a preset font, from which will be taken all the character properties. This attribute is deprecated and it is there only for compatibility reason (that’s why it the label is strukethrough. In order to define a particular style of text to use all over your document, use a style.

The sample of using markup is here.

You can use style for setting:

 

  • Common properties
  • Graphics properties
  • Border and padding properties
  • Text propertiesThe another sample is here.

    DynamicJasper API using

    In case using DynamicJasper API you can set style with help of ar.com.fdvs.dj.domain.builders.ColumnBuilder class:
    [code type=java]
    AbstractColumn columnState = ColumnBuilder.getNew()
    .addColumnProperty(“state”, String.class.getName())
    .addTitle(“State”).addWidth(new Integer(85))
    .addStyle(detailStyle).addHeaderStyle(headerStyle).build();

    The sample is here.

    JasperReports API using

    In case using JasperReports API you can set style, for example, with help of net.sf.jasperreports.engine.base .JRBasePrintText class:
    [code type=java]
    JRPrintText text = new JRBasePrintText(jasperPrint.getDefaultStyleProvider());
    text.setStyle(boldStyle);

    The sample is here.

 

Building web apps with Rails4 and AngularJS in 15 minutes

While learning AngularJS to make a single page app using Rails4, I found some good videos and blogs. However, I did not find any simple example for CRUD operations that made me easily understand the integration between Rails4 and AngularJS. So in this tutorial post, I explain how to create basic CRUD operation using Rails4 and AngularJS.

Here is my git repository for the complete code Github

Create rails project
[code type=ruby]rails new rails4_crud_with_angularjs

Create User model
[code type=ruby]rails g model user

file db/migrate/[timestamp]_create_users.rb
[code type=ruby]
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :first_name t.string :last_name t.string :email t.string :phone t.timestamps end end end

[code type=ruby]rake db:migrate

app/model/user.rb
[code type=ruby]
class User < ActiveRecord::Base validates :first_name, :last_name, :email, presence: true end

Create Users controller
[code type=ruby]rails g controller users

Create the CRUD operation in users controller and send JSON response. The code sample is here

Add angular gem

In Gemfile add these two gems.

gem 'angularjs-rails'
gem 'angular-ui-bootstrap-rails' #for bootstrap UI
bundle install

Setup layout

Adding ng-app and ng-view indicates that we have an AngularJS app in the page.
[code type=ruby]


Rails4CrudWithAngularjs
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>

<%= yield %>


Create an angular controller

First let’s create a directory for our controllers. You can name it whatever you want.

mkdir -p app/assets/javascripts/angular/controllers

Now create users_controllers.js file. Here I have used the same naming convention as Rails.
[code type=javascript]
// app/assets/javascripts/angular/controllers/users_controllers.js
var myApp = angular.module(‘myapplication’, [‘ngRoute’, ‘ngResource’]);

‘myapplication’ is ng-app name.

Add Factory

Factory is the angular provider and you can learn more about it here. It basically interacts with the rails server and processes the json response.
[code type=javascript]
myApp.factory(‘Users’, [‘$resource’,function($resource){
return $resource(‘/users.json’, {},{
query: { method: ‘GET’, isArray: true },
create: { method: ‘POST’ }
})
}]);
myApp.factory(‘User’, [‘$resource’, function($resource){
return $resource(‘/users/:id.json’, {}, {
show: { method: ‘GET’ },
update: { method: ‘PUT’, params: {id: ‘@id’} },
delete: { method: ‘DELETE’, params: {id: ‘@id’} }
});
}]);

‘Users’ factory is used for getting the collection of users and creating users. ‘User’ factory is used to get the user details, update the user or delete the user.

Add Routes

Angular routes are used for deep-linking URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.
[code type=javascript]
myApp.config([
‘$routeProvider’, ‘$locationProvider’, function($routeProvider, $locationProvider) {
$routeProvider.when(‘/users’,{
templateUrl: ‘/templates/users/index.html’,
controller: ‘UserListCtr’
});
$routeProvider.when(‘/users/new’, {
templateUrl: ‘/templates/users/new.html’,
controller: ‘UserAddCtr’
});
$routeProvider.when(‘/users/:id/edit’, {
templateUrl: ‘/templates/users/edit.html’,
controller: “UserUpdateCtr”
});
$routeProvider.otherwise({
redirectTo: ‘/users’
});
}
]);

In the code above, I have added the controllers UserListCtr, UserAddCtr, UserUpdateCtrfor listing users and to create and update users.

Add Angular templates

Now we need to add templates. I have stored them in public/templates.

If we create a file public/templates/users/index.html with some arbitrary content, we should be able to see it in the browser. Here is a sample template for users.

 CRUD Actions

Now our setup is done and we are ready for processing CRUD operation.

Index Action:
[code type=javascript]
myApp.controller(“UserListCtr”, [‘$scope’, ‘$resource’, ‘Users’, ‘User’, ‘$location’, function($scope, $resource, Users, User, $location) {
$scope.users = Users.query(); //it’s getting user collection
}]);

‘UserListCtr’ this controller listing users. you can check index.html here I am not explaining index template it’s straight forward angular template, you can read more about it here.

Create Action:
[code type=javascript]
myApp.controller(“UserAddCtr”, [‘$scope’, ‘$resource’, ‘Users’, ‘$location’, function($scope, $resource, Users, $location) {
$scope.save = function () {
if ($scope.userForm.$valid){
Users.create({user: $scope.user}, function(){
$location.path(‘/’);
}, function(error){
console.log(error)
});
}
}
}]);

‘UserAddCtr’ this controller create user. you can check new.html here. Users.create() calling users controller create action. create() action we defined in ‘Users’ factory.

Update Action:
[code type=javascript]
myApp.controller(“UserUpdateCtr”, [‘$scope’, ‘$resource’, ‘User’, ‘$location’, ‘$routeParams’, function($scope, $resource, User, $location, $routeParams) {
$scope.user = User.get({id: $routeParams.id})
$scope.update = function(){
if ($scope.userForm.$valid){
User.update($scope.user,function(){
$location.path(‘/’);
}, function(error) {
console.log(error)
});
}
};
}]);

‘UserUpdateCtr’ this controller update the user. you can check edit.html here. Users.update() calling users controller update action. update() action we defined in ‘User’ factory.

Delete Action:

For delete user I am not creating separate angular controller. I am writing deleteUser event in ‘UserListCtr’  controller.
[code type=javascript]
myApp.controller(“UserListCtr”, [‘$scope’, ‘$http’, ‘$resource’, ‘Users’, ‘User’, ‘$location’, function($scope, $http, $resource, Users, User, $location) {
$scope.users = Users.query();
$scope.deleteUser = function (userId) {
if (confirm(“Are you sure you want to delete this user?”)){
User.delete({ id: userId }, function(){
$scope.users = Users.query(); // after delete user get users collection.
$location.path(‘/’);
});
}
};
}]);

User.delete() calling users controller destroy action. delete() action we defined in ‘User’ factory.

In  public/templates/users/index.html for adding ‘Remove’ link
[code type=html]Remove

Remember href should be blank, if you add href=”#” it will call default route in your application.

I hope this blog helps those are started development in Rails + AngularJS.