On Rails 5, webpacker and I18n-js

Standard

So, webpacker is landing for Rails 5 (and will be part of Rails 5.1 core), which is really exciting news for frontend development with Rails backend.

I am building a project which heavily relies on I18n and multiple languages.
Assuming you know how to I18n your rails project, you’d need to use the yml files also on your react frontend.
This is how I have solved the I18n for Javascript and React:

First install I18n-js, with

yarn add i18n-js

Next, I have exposed my Rails locale to javascript globally by adding to application.html.erb (or any of your layout files). Inside script tag:

window.locale = '<%= I18n.locale.to_s %>'

(now on javascript console, you could check with locale or windows.locale)

Next, I needed to be able to read the translation yml file, so I have installed the yaml and json loader via:

yarn add yaml-loader json-loader

To configure them I have created a loader file in config/webpack/loaders/yaml.js which looks like:

module.exports = {
 test: /\.ya?ml$/,
 loaders: ['json-loader', 'yaml-loader']
}

this will enable me to read from yaml files.

Now I want to add to my react app, I18n and load the translations.
I have created a translations.js file in my components directory:

import I18n from "i18n-js";
import { en } from "../../../config/locales/en.yml";
import { pirate } from "../../../config/locales/pirate.yml";

I18n.locale = window.locale;
I18n.translations = { 'en': en, 'pirate': pirate }

export default I18n;

And boom I have I18n all ready for my react app.

On each component I import the translations with import I18n from './translations';
and when I need translated text I simply use { I18n.t('hello') }

Making of….מהחקלאי , open sourcing it, and request for help…

Standard

tl;dr… We have created an open source mobile apps to empower Israeli farmers who sell directly to customers

A while back Hila Aflalo (my wife) and I have talked on how we can help the farmers protest (Hebrew) in Israel. We then met awesome Orli Yakuel, on another issue, and asked if she’d like to help with building the product and the user experience. (Of course she said yes…).

The task was to get to market as soon as possible. We wanted to help the farmers as soon as possible, and we also wanted to show them our support.

I chose Rails 5 API to power the backend of our application and ionic framework to build the mobile apps.

Both Android and iOS apps are now public, yet all of the above (including the farmers) feel that this is a very basic version which can be extended for the benefit of everyone: customers and farmers.

So, we would love if you could help us with improving, fixing and extending מהחקלאי applications:
We have created a trello board to manage our effort: https://trello.com/b/8Lp50uqc/-

(Join to Trello here)

The source code for the Rails API: https://github.com/shlomizadok/agri_api
The source code for the Ionic App: https://github.com/shlomizadok/agri

So, you know the drill (ping me for help):
Fork, clone, improve, pull request.

What do you need to know:

  • The backend is made of Rails. It is pretty much easy to pick – If you feel it is a hustle, maybe we can set a test environment somewhere (Heroku)
  • Ionic is the beautiful, open source mobile SDK for developing native and progressive web apps.
  • We relay heavily on Angular 1.x for the mobile App

 

A quick hack on adding a link to Waze from your ionic app

Standard

I am building an application which shows addresses on a map (more on that on a different post…).
I chose to build it with ionic framework, as it is really a very simple HTML5 application.

One of the feature requests was to add a “Navigate with Waze” button for each address.

I searched for an ionic integration with Waze, and found one which didn’t work as (I) expected.

Searching in forums made me discover…

You do not need a special integration with Waze – Waze has a beautiful mechanism that will open Waze whenever you’re calling
http://waze.to/?ll=latitude,longitude&navigate=yes

That it!

So from my app I can create a button or a link with
href=”http://waze.to/?ll=32.1854841,34.8522185&navigate=yes“, and if you have Waze installed it will open the navigation to the latitude/longiute you have provided (It this case to Red Hat Israel office…)

on Ionic, Parse and Facebook login

Standard

Totally newbies glossary:
1. Parse – Parse Server is an open source version of the Parse backend that can be deployed to any infrastructure that can run Node.js. Parse Server works with the Express web application framework. It can be added to existing web applications, or run by itself.
2. Ionic – Free and open source, Ionic offers a library of mobile-optimized HTML, CSS and JS components and tools for building highly interactive native and progressive web apps. Built with Sass, optimized for AngularJS.
3. Facebook – A privacy reseller 🙂

So the goal:
An android application, with Facebook login and Parse as a backend.

Step 1: Setting a Parse server.
You’ve probably heard, Facebook has decided to open source Parse server (and terminate it’s service).
Getting and running a local parse server is done with:

$ npm install -g parse-server mongodb-runner
$ mongodb-runner start
$ parse-server --appId APPLICATION_ID --masterKey MASTER_KEY

(you can replace the appId and masterKey to something more meaningful, should you want…)
But basically, that it. You’ve got a parse server up & running.
You can test it with sending a new POST request to save data:

curl -X POST \
-H "X-Parse-Application-Id: APPLICATION_ID" \
-H "Content-Type: application/json" \
-d '{"age":37,"patientName":"Sean Plott","illnessType":"Flu"}' \
http://localhost:1337/parse/classes/PatientCard

You will get a response with the object id and creation date.
(Ain’t that great?)

Step 2: Setting ionic application
Ionic is a wonderful framework for building hybrid mobile applications (e.g., use my beloved HTML, CSS and JavaScript to build a mobile app). Ionic is one of many hybrid frameworks, but I believe that (at least for both Android & iOS) it is the coolest and maturest.

From Ionic framework getting started, install ionic:

$ npm install -g cordova ionic

Once installed, start an empty ionic project:

$ ionic start myFacebookApp blank
  • You can create a blank, tabs, sidemenu apps

Once initialized, cd into the app and add Android / iOS by running:

$ ionic platform add android

/me cannot add ios on my Fedora, so added only android.

At this point you should also add Android (& iOS if using) environment. Easiest way would be to download Android Studio and SDK from Android developers website.

You can test your newly created app by running

$ ionic serve

this will open a browser tab with http://localhost:8100 (Keep this open, it will live reload with changes 🙂 ).

At this point I should remember to say that ionic relies heavily on AngularJS – that’s like its secret sauce.

Ionic’s directory structure:

The most important place is the ‘www’, this is where our hybrid app lives. The other “here be dragons” directories and files are the Android -> Cordova -> www connections and enablers (May cover those on a separate post).
So, the directory that will interest us most is the ‘www’ directory.
‘www’ directory is made of index.html (the entry point, eh?), css, img, js & lib directories. All of them are quite self-explanatory 😀

Step 3: Connecting Parse and Ionic

As we are building a JavaScript application, we need Parse’s JavaScript SDK.
I have cd’ed into www/js and downloaded latest Parse JavaScript SDK:

$ wget https://parse.com/downloads/javascript/parse-1.6.14.js -O parse.js

While talking about Parse JavaScript SDK, take a minute to look at their guides at https://parse.com/docs/js/guide

Now we have to tell ionic about Parse’s JavaScript. I have added it into my index.html (right above the <script src=”js/app.js”></script>:

<script src=”js/parse.js”></script>
<script>
Parse.initialize(“APPLICATION_ID”);
Parse.serverURL = ‘http://localhost:1337/parse/’;
</script>

So, the first part is adding the SDK. The second part is initializing Parse with my application id, and url (The url addition is since Parse can run anywhere this days…)

Next, I wanted to ensure that my ionic and parse play nicely.
I have followed a short tutorial from https://www.thepolyglotdeveloper.com/2015/04/use-parse-core-in-ionic-framework-mobile-apps/ — (note the changes in Parse initialize…)

Everything worked superb on my http://localhost:8100 and I have decided to give it a try on the Android emulator. I have ran:

$ ionic emulate android

It took some time to build and run, and once it was app running on the emulator. It didn’t work! 🙁
The app was trying to access http://localhost:1337, which it couldn’t.
So I had to change from Parse.serverURL = ‘http://localhost:1337/parse/’;
to Parse.serverURL = ‘http://10.0.2.2:1337/parse/’;
(On android emulator, 10.0.2.2 is a special alias to your host loopback interface).

That obviously broke my http://localhost:8100… so I went to Heroku for the help.
(which was easy as a click )

Now I have change the Parse.serverURL to the Heroku’s URL and it worked well on both the emulator and the browser.

Step 3 (Or 4 is it?): Facebook login

First, you’d have to create an app on Facebook. You should gain the APP_ID and APP_NAME

So, I’ve been smart and followed Parse’ excellent document on Users and Facebook login – https://parse.com/docs/js/guide#users-facebook-users

Yeah, well, that works only on the browser and does not work on the emulator (nor on the phone).

But as ionic is relayed on Cordova, we can use it to add Angular – Cordova integration with:

$ bower install ngCordova

this will install a set of tool to make Angular and Cordova play nicely together.
Next we need to update our index.html with the new ngCordova JavaScript files
(right below <script src=”cordova.js”></script>) so it looks like:

<script src="cordova.js"></script>
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
Next, we’d have to add Cordova’s facebook plugin. Usually you’d do it with “cordova plugin add pluginname”, alas I have learnt it may break the FacebookSDK (wat?)
To achieve that we’d go one directory up (above the www) and do:
$ git clone https://github.com/Wizcorp/phonegap-facebook-plugin.git
(this will download the plugin)

$ cordova -d plugin add phonegap-facebook-plugin \ 
--variable APP_ID="FB_APP_ID" --variable APP_NAME="FB_APP_NAME"

Where FB_APP_ID and FB_APP_NAME are the ID and Name of your Facebook app.

Now I have added a function to do the Facebook login. In my app.js it looks like:

$scope.FacebookLogin = function(){
  $cordovaFacebook.login(["public_profile", "email"]).then(function(success){
    var expiresIn = success.authResponse.expiresIn;
var expDate = new Date( new Date().getTime() + expiresIn * 1000).toISOString();
    varfacebookAuthData = {
      "id": success.authResponse.userID,
      "access_token": success.authResponse.accessToken,
      "expiration_date": expdate
    };
    Parse.FacebookUtils.logIn(facebookAuthData, {
      success: function(user) {
        console.log(user);
        if(!user.existed()) {
          alert("User signed up and logged in through Facebook!");
        } else{
          alert("User logged in through Facebook!");
        }
      },
      error: function(user, error) {
        alert("User cancelled the Facebook login or did not fully authorize.");
      }
    });
  }, function(error){
    console.log(error);
  });
};
This has been wired to on a new button:
<button class=”button” ng-click=”FacebookLogin()”>Login with Facebook</button>
And, voila! We have a working Facebook login on our little ionic app.

Foreman integration with Slack

Standard

I have created a little plugin which sends events from Foreman to Slack.
It currently supports one event – “Host is built” event.

It can be found for testing at https://github.com/shlomizadok/foreman_slack

The reasoning behind this plugin is that, Slack is more than a communication tool between teams. It is a focal point for teams, dev-ops and systems.
This is where they find out what’s up with their systems – See for instance how popular PagerDuty’s Slack bot is.

Anyhow, I am sure that any team who has Foreman and Slack would love to see events sent from Foreman to Slack.

It requires little configuration to get a webhook_url to your channel.

  1. Go to https://slack.com/apps/A0F7XDUAZ-incoming-webhooks
  2. Choose your team, press configure
  3. In configurations press add configuration
  4. Choose channel, press “Add Incoming WebHooks integration”

Once you’ve got an Incoming webhook URL, you can add it to Foreman (see /settings #Slack tab).
And you can test that is is working by going to http://<your_foreman>/slack_test
It will send an “Ahoy” message to your selected channel.
If everything looks okay, on the next host you will create – you will get a message on your Slack channel once the host is built.
foreman slack message

The first event I chose was “Host is built”. I plan to also add the “Puppet error state”.
Which events do you think I should add next?

Will 2016 be the year of Go?

Standard

TL;DR – Go is six years old. Will it gain popularity like javascript / ruby this year?

So, Golang is 6 yrs. old. It is mature, it is robust and performant.
However, it seems to me that it didn’t catch as a server-side language as Ruby and Javascript.

(Though, looking at the chart below show high volume for Go in comparing the three)

So the question pops up is why Ruby & javascript became so popular?
Humbly, I’ll try to raise errors  two points and discuss them:

  • High learning curve. Both Ruby and javascript are super easy to learn, run and deploy (as well as PHP)
    I think that because it is a very much C type language, it may scare newbies from approaching and trying
  • Lack of an easy, cool, and well promoted web framework (Where was Ruby without Rails? Where we so happy building a node backend w/o mean.io || Express.js || meteor ?)

And while writing those two points, I thought: “Maybe Go shouldn’t be your (my) next server-side language?”
I mean, if it was designed to be a systems programming language, maybe it should stay there?
(though one can argue that both Java, C#, Erlang and others have their own web frameworks).

Blah, this blog post rose more questions than answers….

My unsure, undecided conclusion is that if Go would have an easy web framework (as easy as Rails) 2016 may be the year of the Go.

Happy 6th. Birthday, Go!

How intimate are you with your smart-proxy?

Standard

The smart proxy is a crucial service on the Foreman.
It provides us an API to subsystems such as DNS, DHCP, TFTP, realms, templates, BMC, Puppet and is extendable with plugins.

Up until now, we had no visible data on what is going on with our smart-proxy and what is its status, version and plugins.

Well, that is changing…
We have added a new feature (which is a part of set of related features) which will help us to learn more about the status of our smart-proxy.

(* Talk is cheap, whiskey is money) Screenshots:

Proxies index:

Smart Proxies index

Smart Proxies index

Here we have added the status column, so right on you could know if your proxy is up and running (and if not, why…)

Proxy show page:

Proxy overview

Proxy overview

When clicking on a proxy on the index page, we are now being redirected to the Proxy’s show page (until now we were redirected to its edit page).
Here we get a glimpse of the proxy’s status: its URL, version and running features.

Clicking on the “Services” tab will open:

Services tab

Services tab

Which gives us some more info on our proxy’s features.

This is a work in progress which will be expanded in the next few weeks,
and will land at #theforeman 1.11

Pipelines at Heroku

Standard

Aren’t Heroku brilliant?

A while back, while in Learni, we’ve created three servers on Heroku: One for the devs to test their code, one for QE to test (e.g., staging) before production and of course a production one. Once the dev felt comfortable with the code, we pushed it to QE and after (hopefully not…) fixing cycle, we’ve pushed it to production.

Now I discover that Heroku “copied” us and created pipelines.

So pipeline do exactly what’s described above: You create three servers and add them into a pipeline.
You’d of course start with pushing to the dev server and from there you could promote to staging and so fourth.
Pipeline enables you to push for more than one dev into staging as you may want to support github flow (you want to support github flow 🙂 )

And as always in Heroku, it comes with great CLI integration.

One thing I’d love to have is other integrations besides github (gitlab, bitbucket and other flavors)

Anyhow, well played Heroku !

via GIPHY

A weekend with Go lang, BeeGo & React

Standard

So I’ve decided this weekend to take Go language for a ride.

I have started with Go’s awesome tour to understand what it is all about. To be honest it is quite different from my daily Ruby, yet cool enough to get me in.

Why Go and not Node.js?

the $1 million question, right?
I have never written anything big in Node, nor in Go so I am not familiar with real-life problems. I have done some mini projects to figure out what Node is all about and I love Node’s ecosystem. My friends from mean.io have done some amazing stuff with Node.
My 2 cents answer to the question: “I am afraid of Node’s callback nightmare” + I want to learn something new + some cool projects @work are in Go (openshift) to name one.

So, once I’ve comlpeted the tutorial, I have decided on my weekend project: A blog!
I mean, we never have enough of how to create blogging system 🙂

Next, I started looking for a go web framework. This is a bad practice because you can build everything in Go. from my minimal understanding those frameworks are mainly wrappers to existing libraries in Go.
There are quite a few Go frameworks: Beego, Martini, Gorilla, Revel & GoCraft to name a few. However, more experienced Go developers will tend towards Go’s Net/HTTP.
After some reading (and because I like honey), I chose Beego which seemed the easier choice for a newbie.

Hello 

Installing in Go is quite simple, you just run:

go get github.com/astaxie/beego
go get github.com/astaxie/bee (cli)

And now you’ve go two options to start a new project:
> bee new myproject – to create a new MVC ( where the view is HTML)
Or
> bee api myproject  – to create a new MVC API (so the view is JSON)

I chose the API project, as I wanted to use React as my frontend.
I have deleted all the demo controllers & models and started from scratch.

The Model:
It took me sometime to get to this model, and I am sure I can make it better (contributions welcome). And so I have crafted struggled my way to create a CRUD API which displays, creates, updates and deletes Posts. The Controller:

Finally, I had an API responding to “/v1/posts”.

Next was React.
I have followed their fine tutorial and moved it from comments (the tutorial) to Posts.
The React app looks like:

The final outcome is at: https://github.com/shlomizadok/beego_react
(fork, learn, make better 🙂 )

Eventually, I have pushed it to Heroku so others can try.
https://fathomless-taiga-3095.herokuapp.com/
Try it (and write something nice…)