(Physically) Printing with Ruby!

Recently, we were asked to develop an application that would silently print to a physical printer (in this case, a Zebra ZR203) on a Windows computer. The aim of the program was to use it to print coupons in conjunction with a touch screen computer.

One way we considered doing this was by using the Zebra Programming Language (ZPL) to create the label, connect the Zebra printer to the LAN, and sending it to TCP port 9100 on the printer. However, this method could get very messy when deploying the finished product to dozens of locations. We needed the setup to be as trouble-free as possible.

I found Foxit, a (Windows only) PDF reader, which conveniently allows for command line printing. Together with the great PDF generator gem, Prawn, I generated a PDF from the coupon PNG image:
Prawn::Document.generate("coupon.pdf", :page_size => [225, 1132], :margin => [0,0,0,0]) do |pdf|
    pdf.image("coupon.png", :fit => [225, 1132])
end
and executed a system command using Ruby’s “system” command:
	system("\"C:\\Program Files (x86)\\Foxit Software\\Foxit Reader\\Foxit Reader.exe\" /t \"coupon.pdf\"")
Of course this command depends on the install location of Foxit, but Program Files (x86) is the default location. This command will print to the current default printer, but you can specifiy a printer by appending its name to the end of the command like so:
   system("\"C:\\Program Files (x86)\\Foxit Software\\Foxit Reader\\Foxit Reader.exe\" /t \"coupon.pdf\" "#{printerName}" ")
Finally, we had this small application running locally with Sinatra, and had the frontend perform Ajax GET requests to the backend:
$.get('http://localhost:4567/print', (data) ->)
And that’s it!

Keep you up-to-date or…get lost! (PHP won’t forgive!)

PHP is getting some pretty nice feature on each new release.

However most of the versions provided by the hosting providers don’t perfectly align with the evolution of the language.

In this situation you should really take care on how you write your code!

One example?

Function array dereferencing or if you prefer:

foo()[0]

You like it eh ;)

Unfortunately this is available only up from version 5.4.0.

If you’re handling some projects that are hosted on servers shipping an older version of the one over mentioned 5.4.0 think twice before start doing what you like :P

P.S: self experienced ;)

Rails 4.1 ActiveRecord enums

Rails 4.1 has recently been released and it came out with the usual bag of goodies, one of the most notable being ActiveRecord enums, a handy new feature that simplifies the creation and use of state attributes for your models.

Consider the following use case: our app needs users, and each of them has a state that can be registered, active or blocked.

How would have we addressed the task in the past? Well, probably by adding a string or integer field to the users table in order to hold the state value, and by writing a few scope methods to query the table. Nowadays it’s much simpler: you just need to write a migration that adds the field to the table:


class AddStatus < ActiveRecord::Migration
  def change
    add_column :users, :state, :integer
  end
end

and add the enum macro to the User class:


class User
  enum state: [:registered, :active, :blocked]
end

Let’s see in details what we’re getting. The user state is nil by default; we can query each state label to see if it matches the current user’s state:


user = User.new
user.state
 # => nil

user.registered?
 # => false

user.state = :registered
user.registered?
 # => true

Want to update the state and save the record in one command? Easy enough:


user.registered!
user.persisted?
 # => true
user.registered?
 # => true

We also get handy scope methods for each state:


User.active
 # => #<ActiveRecord::Relation []>
User.registered
 # => #<ActiveRecord::Relation [#<User id: 7, status: 0...]>

We can even create users with a specific state using the enum scopes:


User.registered.create
 # => #<User id: 6, status: 1, ...>

Can we inspect the actual state column value, before typecast? Of course we can, but #state_before_type_cast returns the enum label. So we’re going to use the [] method:


user.state
 # => "registered"
user.state_before_type_cast
 # => "registered"
user[:state]
 # => 0

So, now we can fully understand how it works: ActiveRecord actually stores in the database the integer corresponding to the enum label position inside the array that we provided to the <code>enum</code> macro.

Do you want a default value? Then add a default value to the state field:


class ChangeStatus < ActiveRecord::Migration
  def change
    change_column :users, :status, :integer, default: 1
  end
end

From now on all instantiated users will have a default state value corresponding to the position we provided in the migration:


user = User.new
user.state
 # => "active"

Be aware there are a few reserved words that cannot be used as enum labels, most notably existing column names, existing class methods and a few more. If you happen to use one of them by mistake then the app will complain raising an error:


class User
  enum state: [:logger]
end
 # => ArgumentError: You tried to define an enum named "state" on the model "User", but this will generate a class method "logger", which is already defined by Active Record.

If you are interested in the actual Rails implementation you can peep at the code and  tests on the github repository, of course. Have fun!

Taming the Processing loop

In Mikamai we do a lot of reasearch on non conventional hardware, we make prototypes and create unusual interfaces that are very domain specific.

Like this one

image

Seriously, we did it.

To quickly sketch ideas, we often rely on Processing, it’s super easy and its loop based execution model gives the feeling of programming a video game.
The drawback is that it is so fast to get something working, that you will be tempted to make the mistake of creating a polished prototpe.
Your prototype code ends up in production and there’s no way back from there.

To resist the temptation of releasing a blob of code, I borrowed a technique from one of the Rob Pike’s talks to keep things easy, while keeping them clean at the same time.

It is basically an implementation of a state machime.
We’re gonna have a StateMachine class that handles the inputs and the state changes, and several state classes that implement the State interface.
The interface is very simple and contains only one method

interface State {
      public State nextState();  
}

The loop of our Processing application is really simple too

StateMachine sm = new StateMachine(initialstate);
void draw() {
  sm = sm.nextState();  
}

and this is the most basic implementation possible of the StateMachine class

class StateMachine(State initialstate) {
  private State currentstate;

  StateMachine(State initialstate) {
    this.currentstate = initialstate;
  }

  public StateMachine nextState() {
    this.currentstate = this.currentstate.nextState();
    return this; 
  }
}

Each class must implement the nextState method and return an istance of the next state that will be executed.
With this knowledge in mind, this is how you build an infinite loop inside an inifinite loop

class InfiniteLoopState implements State {
    public State nextState() {
        return this;
    }
}

But we can do better!
How about a ping pong?

class Ping implements State {
    public State nextState() {
        println("ping?");
        return new PongState();
    }
}

class Pong implements State {
    public State nextState() {
        println("pong!");
        return new PingState();
    }
}

We moved the logic of the application out of the central switch/case statement in the draw function and deconstruted it into smaller pieces, that only know about themselves and the next state they are going to emit.

As long as your state classes implement the State interface you can exapnd the concept to fit your needs.
For example, if you need to keep track of the environment and/or the previous state, you can adjust the State interface to support it.

interface State {
      public State nextState(State previousstate, StateMachine sm);  
      // StateMachine holds the environment for us
}

and modify StateMachine accordingly

  public StateMachine nextState() {
    this.currentstate = this.currentstate.nextState(this.currentstate, this);
    return this; 
  }

TL;DR: state machines are easy, use them!

You can find examples on how to use this pattern and how to add more features in the github repository.

Harder Better Faster Stronger!…most of all Faster!!! Jetzt!

Do you find yourself slow at reading?

If the answer is yes, well, you’re definitely not alone!

(Oh my I feel like a television seller…)

However I’m also slow at reading!

Willingly to became faster I started to look around and read (slowly :P) articles related to the possibility to increase my reading speed.

Most of them reported good practices and exercises and some of them even reported tools and programs (e.g. desktop and mobile apps) able to help in increasing the reading speed.

Among them I’ve found a really interesting Chrome extension called Jetzt.

Sincerely I really felt in love with it!

It’s easy to install, to use and is evolving pretty fast!

Once loaded into Chrome you can simply invoke it by selecting some text in a Web page and press the keyboard combination Alt-s. Try it! :)

The algorithm on which it founds its roots is able to take into consideration the punctuation and so it’s able to grant a really pleasing reading experience.

If you like it like or if you simply find some bugs don’t hesitate to contribute ;)