A simple html/js binding system using Reactive Programming with ProAct.js

Yeah! We are going to talk about Reactive Programming, even doing something with it!!!

So I’m proud to announce that ProAct.js – my RP implementation is production-ready. At the time of this post the most recent version is 1.2.1

So… What is Reactive Programming -> it is programming based on the data flow. To put it simple, everything is data, users read data, create data, update data, delete data, your system deals with it in some way. Using The Reactive Paradigm we just say in a declarative way, which part of the data depends on which and the program deals with changes (data flow) by itself. It’s a kind of magic!

And what is ProAct.js?
It is implementation of this Reactive Way in JavaScript, using both object oriented and functional approaches – you’ll see.

We are going to implement Html bindings using ProAct.js and jQuery/zepto. We can do it without jQuery/zepto but it is easier that way.
We are going to use two of the features ProAct.js gives us. The first one is Reactive Objects – these are normal JavaScript objects but with magical fields that can depend on one-another called ‘Properties’ (The ‘Pro’ from ProAct.js comes from them).

Here is an example:

var obj = ProAct.prob({
 x: 4,
 y: 5,
 z: function () {
   return this.x + this.y;
 }
});
// obj.z is not a function any more it is a magical field!
console.log(obj.z); // 9 (4 + 5)
obj.x = 10;
console.log(obj.z); // 15 (10 + 5)
obj.y = 15;
console.log(obj.z); // 25 (10 + 15)

The other feature is the FRP Streams. The example with streams will use our bindings.

Let’s begin!
The code for the bindings with example how to use them is in this fiddle.
Our main purpose is to create a ProAct.Bindings namespace, containing the logic. So everything will go in a module like this:

(function (window, ProAct, $) {
 'use strict';
})(window, ProAct, $);

Our main function that we’ll export is ‘ProAct.Bindings.create($el, context)’. We define it like that:

 function create($el, obj) {
   var $bindings = $el.find('[pro-bind]').add($el.filter('[pro-bind]')); // 1

   $bindings.each(function () {
     setupBinding($(this), obj); // 2
   });
 }

 ProAct.Bindings = {
   create: create
 };

We are going to use a context object, containing the bound fields and tags with attributes ‘pro-bind='<field>’.
So for example if we want to bind obj.z from the Reactive Objects example to a span tag’s content, the tag will look like like that:
‘<span class=”test” pro-bind=”z”></span>’
and we are going to call our main function like that:
ProAct.Bindings.create($(‘.test’), obj);
And voila – changing obj.z will update the html. At least if we implement it!

What does ‘create‘ do?
1. It queries all the children of the passed element that have ‘pro-bind’ attribute and the element itself, if it has the attribute.
For every element queried it
2. calls ‘setupBinding’ with the element and the context object.

Let’s define setupBinding:

 function setupBinding($binding, obj) {
   var property = $binding.attr('pro-bind'); // 1

   if (!obj.p(property)) {
     return; // 2
   }

   onProp($binding, obj, property); // 3
 }

This function
1. gets the value of the ‘pro-bind’ attribute. This is the name of the context’s field.
2. if there is no such field in the context it does nothing,
3. if there is – it calls another function ‘onProp’ with the bound element, the context and the name of the field.
We use the special ‘p’ function of the Reactive Objects here to check if given Property exists. More on that in another post.

We continue, defining ‘onProp’:

 function onProp($binding, obj, property, safe) {
   var tag = $binding.prop('tagName').toLowerCase(); // 1

   obj.p(property).on(function () { // 2
     if (tag === 'input') { // 3
       $binding.prop('value', obj[property]);
     } else {
       $binding.text(obj[property]);
     }
   });

   obj.p(property).update(); // 4
 }

Here we define the actual binding between the property of the context object and the html.
1. First we get the tag of the html element.
2. Using the ‘p‘ method of the Reactive context we get the actual Property representing the field to bind and add a listener to its changes.
3. When the Property changes we update the html element. If the tag is input we update its value, otherwise we update the text content of the element.
4. We call ‘update’ on the Property representing the bound field to sync its value to the html content.

This is it. Now we can write html like this:

 <div class="sum">
   <p>The result of <span pro-bind="x"></span> + <span pro-bind="y"></span> is <span pro-bind="z"></span>
  </p>
</div>

And bind object to it like this:

var sum = ProAct.prob({
 x: 4,
 y: 5,
 z: function () {
   return this.x + this.y;
 }
});

ProAct.Bindings.create($('.sum'), sum);

Changing sum’s x, or y will update the html.
But how to change x and y using input tags? We will use the second feature, I mentioned – the FRP streams:

function intVal(e) { // 1
 var val = parseInt(e.target.value, 10);

 return isNaN(val) ? 0 : val;
}

var xStream = new ProAct.Stream(); // 2
var yStream = new ProAct.Stream();

sum.p('x').into(xStream.map(intVal)); // 3
sum.p('y').into(yStream.map(intVal));

window.App = { // 4
 x: xStream,
 y: yStream
};

1. First we will define a mapping function that maps a ‘key up’ event to the value of the input tag, it comes from.
2. Second we create two ProAct.Streams -> one for the sum’s x field and on for the y field.
3. Here we do FRP magic -> on every stream we map the mapping function, so if ‘key up’ event enters the stream, it will be transformed to the value of its input tag. And what comes from the streams goes to the value of the corresponding sum’s Property. (This is magic but I’m going to write posts/docs explaining what’s happening).
4. We export the two streams to be easy to use them in the html.

And this is the html:

<input name="x" type="text" onkeyup="App.x.trigger(event)" pro-bind="x" />
<input name="y" type="text" onkeyup="App.y.trigger(event)" pro-bind="y" />

So on keyup event we trigger the event into the streams, it is transformed to the value of its target input tag and the right Property’s value is set to this value.

This is it. We have actual, working bindings. The example from the fiddle is a bit more complex and you can play with it.

I’m sorry if the examples in this post feel a bit magical, but the idea is to show you just how powerful ProAct.js is and what you can do with it, not how it works.
If you’re interested, it has some API documentation.

Useful Links:

  1. ProAct.js – http://proactjs.github.io
  2. Bacon.js FRP implementation more rich and powerful than the current ProAct.js one – http://baconjs.github.io
  3. Kefir.js – Another FRP implementation – http://pozadi.github.io/kefir

Inheritance in JavaScript – A Cool Way

So, JavaScript is a strange language. This prototyping stuff is new for everyone coming from another ecosystem. But it’s not so complex. There are many libraries that provide extending ‘class‘ methods that mimic extending from more conventional languages, like Java for example. (Example of such method is Ember’s Ember.Object.extend)

Now I’m going to show you how to write such an inheritance method in JavaScript and how to use it. In the meantime we will see how prototyping works.

Let’s begin.

First of all we will define a helper method used to copy the properties from one object to another, overriding the common ones:


function ex (destination, source) {
  var p;

  for (p in source) {
    if (source.hasOwnProperty(p)) {
      destination[p] = source[p];
    }
  }
  return destination;
}

Here we just copy the own properties (not the inherited/prototype ones) from the source object to the destination object. Read more about hasOwnProperty here.

Let’s define our main extending method:


function extend (data, staticData) {
  var parent = this, // 1
      child = function () { // 2
        if (data.initialize) { // 2.1
          data.initialize.apply(this, arguments);
        } else { // 2.2
          parent.apply(this, arguments);
        }
      };

  ex(child, parent); // 3
    
  if (staticData) { // 4
    ex(child, staticData);
  }

  if (!data) { // 5
    data = {};
  }

  child.prototype = ex(Object.create(parent.prototype), data); // 6
  child.prototype.constructor = child; // 7
  child.prototype.__super = parent.prototype; // 8

  return child; // 9
}

The idea is that this method is called on the class to become parent class (you will see in the next example what I am talking about).
It has two parameters – data and staticData.
The data parameter is used to pass instance fields and methods to the child class that may override parent ones.
The staticData is used to define class level fields and methods to the child class.
Let’s see what we are doing:

  1. The parent class is this – the caller of the method.
  2. The child class is defined with a new constructor.
    2.1. If we pass an ‘initialize‘ method as field of the data parameter it is used for the       initialization. So in our inheritance ‘initialize‘ is the constructor method.
    2.2. If not we call the parent’s constructor as super constructor.
  3. We use the previously defined ‘ex‘ function to copy all the parent’s static methods/fields in the child – this includes the ‘extend‘ method as well, so the child can become a parent class too.
  4. If we passed staticData, we copy it to the child class – that way we can override some of the previously copied parent static methods/fields.
  5. If we didn’t pass ‘data‘ parameter assign to it default value – the empty object.
  6. Now it is time for the instance methods and fields – create the child prototype, using the parent’s prototype modified with the passed data.
  7. Set the constructor to the child’s prototype.
  8. Set a pointer to the parent’s prototype – a __super.
  9. OK, the child class is ready – return it.

What are we really doing?
First of all, classes in JavaScript are defined using functions – constructors. Every function can be a constructor. If you call the function preceding it with the new keyword, it creates an instance.
In the constructor, when called with ‘new‘, ‘this‘ points to the instance to be created – so if we define fields or methods on ‘this‘ they become instance ones.

When we have an instance and we call method or read field and it is not found in ‘this‘, it is searched in the prototype object of the constructor of the instance.
So if we define methods or fields in the object, pointed by the prototype field of the constructor function – they become instance ones too.

That’s why copying the parent prototype into the child’s is basically extending the parent into the child.

That’s all – I’m doing all of this in the ‘extend‘ method. Let’s use it!


function Foo (a, b) {//1
  this.a = a;
  this.b = b;
}

Foo.prototype.c = function () {//2
  return this.a + this.b
};

var foo = new Foo(2, 5);//3
console.log(foo.c());//4
  1. We create a new function (class); We assign the passed ‘a‘ and ‘b‘ parameters to this.
  2. We are adding a new instance function ‘c‘ (In the prototype of Foo). It calculates the sum of ‘this.a‘ and ‘this.b‘.
  3. We create a new instance!
  4. The result will be 2+5=7

Now is time for the inheritance!


Foo.extend = extend; //1

Bar = Foo.extend({ //2
  initialize: function (a, b, d) {
    this.__super.constructor(a, b);
    this.d = d;
  },    
  d: 8,
  e: function () {
    return this.a + this.b + this.d;
  }
});

var bar = new Bar(3, 1, 9); //3
console.log(bar.c(), bar.e()); //4
  1. We set the ‘extend‘ function to Foo. Now Foo can be parent class!
  2. We extend Foo passing data with:
    – ‘initialize‘ method (remember – this is your constructor), that calls the super constructor (Foo) with the passed ‘a‘ and ‘b‘ parameters and sets ‘d‘ in ‘this‘.
    – ‘d’ – a new instance field.
    – ‘e‘ – a new instance method, calculating the sum of ‘this.a‘, ‘this.b‘ and ‘this.c‘.
  3. Let’s create a new Bar instance!
  4. We’ll see 3+1=4 and 3+1+9=13

So we have a child class now? Very similar to Ruby or Java isn’t it. We can extend Bar too, it has the ‘extend‘ method inherited from Foo. You can try that in this jsfiddle.

OK that’s it.

Useful Links:

  1. MDN  Javascript – https://developer.mozilla.org/en/docs/Web/JavaScript
  2. Ideas in coder wall – https://coderwall.com/p/ajugeq

SPA : Single Page Application – What, Why and How

It’s been some time since my last post, I feel a little rusty, but I was busy working and learning new stuff. This post will be an abstract thing, and I’m going to quit thinking of a song title-like post titles from now on…

So, What is SPA? Single Page Applications or One Page Applications are something very interesting today. The idea is to have something like desktop app look-and-feel in the browser.

The common web sites work like that (using HTTP):
1. Client makes HTTP request to the server, server responds with the page.
2. User click a link on the current page – new request, new page from the server and so on.
The idea is that the client gets the information on pages, request – whole page, request whole page. But if there is a little change on the current page and we want to see that change, we will have to reload this whole page by following this model. So what to do?

Enter the AJAXAsynchronous JavaScript and XML).
I’m not going to get in the details here, but the browser’s give you the XMLHttpRequest javascript object and you can use it to make request to the server, without reloading the current page or loading a new page. With AJAX we are able to load parts of the current page from the server. Cool.
So imagine a single initial request that downloads a page. This page is the application. Everything else is AJAX requests and loading data represented in some format from the server.
So the model here is:
1. Client makes HTTP request to the server, server responds with the application.
2. The client application asks server for data and markup when it is needed.
So your page can look alike a desktop application with menu bar, status bar, tabs and screens, that are changed via javascript on user actions, the data and the markup for that are provided dynamically by the server.

 

OK, now why we need such a thing?
We can take a look back and we’ll see that the Single Page Application for the web is not a new idea, for example the Java Applets were exactly desktop apps in the browser, the Flex/Flash applications too, Microsoft has their Silverlight, etc.
We can see that people tend to use the browser for almost everything, as time passes I realize that I don’t want to install desktop applications and I want my apps to be OS independent, the browsers are getting more and more capable to be Operating System in the Operating System, OS in the OS if you want… We use Gmail (SPA), mail client (I prefer it over Thunderbird), we use Google Drive, we use Pivotal Tracker, we use e-book readers for the browser, we use MP3 players for the browser, there is the Chrome Store (Every browser tends to have something as a store for plugins and apps), there are the Chrome Book Notebooks (ahead of their time in my opinion, btw)…
Additionally, as a developer I see how the clients want more and more Single Page Applications. They are more flexible and easy to use by their employees and users.
So my thoughts are that the Single Page Applications are tightly bound to the future of the web.

 

But how to code something like this. It is not so easy as a common web site.
Yes it is not, you’ll have to write more and more Javascript or Cofeescript or something that translates to Javascript :).
But as it was for the server side in the recent past : PHP, JSP, ASP – one application is written entirely in one layer and in one file – BAD;
VS
The applications is divided to layers and files, convention over configuration, do not repeat yourself, test driven, etc – Rails, Django, Spring, Symphony, Play, etc – GOOD,
we have frameworks that will help us code a good Single Page Application now.
We have Ember JS (by some contributors to Rails), Angular JS (by Google), Can JS, Backbone, GWT, etc.
The web is growing and everything is getting more complex, the needs of the clients are changing, and there are frameworks to help us, as developers, to adapt.

So I wanted write about the Single Page Apps, because I’m doing a lot of applications like that nowadays and maybe I’ll write about Ember Js and its integration with Rails or Node’s Grunt soon… I hope you found something new in this post. Cheers until the next one!!!

PS. I didn’t forget the Websocket protocol (it is for another post).

Useful Links:

  1. Single Page Application in Wikipedia – http://en.wikipedia.org/wiki/Single-page_application
  2. Ember JS – A Framework For Creating Ambitions Web Apllications – http://emberjs.com
  3. Angular JSHTML Enhanced For Web Apps – http://angularjs.org
  4. Can JS – Build Better Apps Faster – http://canjs.com/
  5. The Bulgarian Twitter page for Ember JS – https://twitter.com/emberjsbulgaria
  6. A SPA for reading ePUB books from Chrome (offline capability), Safari, Android and Windows 8, written by me and my colleges from Astea Solutions – Livemargin Reader Beta

Rails : The Good Books & Docs

Rails is famous framework, you can code something working with ease, everything you need is there, out of the box. Rails is famous, there are famous people around it, and they are talking about how cool it is. You want to be a cool programmer that earns good money doing something pleasant – learn Rails, you want performance – learn Rails, you want to give good estimates and don’t get stuck in heavy configurations – learn Rails… Or so they say, or so you though…

If you want to do something, do it right. I waited a long time before entering the Ruby world, because I had to figure out what I want as a programmer. I love coding, but I’ve made quite a few wrong decisions for the direction. For example if I look back at my jobs and projects I don’t have anything to show you… (maybe except the fine offline reader that me and my than-colleges made). So I want to code things that people use and I want to be a part of a good community, in which sharing knowledge is not a bad thing. I want to have the opportunity to create things that will be used by my fellow programmers or the common people. This is why I chose my last job as ruby developer over the JEE opportunities I had. I saw the language, platform and community as the something I needed at the moment. Then I’ve quit my last job to pursue different goals with Ruby, Rails and Sinatra

Why I’m telling you this, you came here to read about the books that would help you learn Rails, not to listen to the story of a nobody. But in this post I’ll share my thought about some books, so why not share my experience that lead me to them. Think about what you want before learning Rails… If you want to work in a corporate company with big budgets, its not for you. If you want to earn money without giving a thought, it is not for you (try PHP).

If you want to learn Rails, first learn Ruby. Every language has its secrets that you need to know. The language is a tool, you should learn how to use it. The framework is an extension of this tool. So read my post about the good Ruby books and docs if you want.

Now, lets begin:

  1. Agile Web Development with Rails – In this book you will develop your first Rails application on iterations. After that you will learn about the different Rails modules in depth. Very good and easy to read, this is your entrance to Rails. It is written by Sam Ruby and published by The Pragmatic Bookshelf. At the time of this writing there is a beta version of the fifth edition of the book for Rails 4.

  2. The Rails 3 Way – It is both a Rails reference and bag full of advises by professionals. It shows you the way of Rails and good examples how to bend it but not break it. It is written by Obie Fernandez and published by Addison-Wesley. ‘The Rails 4 Way’ is on its way :)
  3. http://railscasts.com – Watch this video casts and there will be no new things in the Rails world for you. By Ryan Bates.
  4. http://railsapps.github.io/tutorial-rails-devise-rspec-cucumber.html – This is the best tutorial about Rails with Rspec and Cucumber I can think of…

I think these four are more than enough. The first one will teach you how to implement your first application and understand how it works, the second one will get you deeper in Rails and how to use it and the third one will show you the whole gem universe around Rails… The fourth one is just good :)

Ruby : The Good Books & Docs

If you want to learn rails, you should learn ruby. If you want to learn ruby or to get more proficient in ruby you should read some books/articles/documentation/sources.
I read quite a few things about ruby, some of these links and books were given to me by my friends and colleges, I want to share them with you…

  1. I recommend “Programming Ruby 1.9 & 2.0” by Dave Thomas, with Chad Fowler and Andy Hunt. This a book from The Pragmatic Bookshelf. The best book about Ruby. It is a complete reference of Ruby and its standard libraries. This is a must. I know that most of the books about programming languages begins with definitions of the key words, conditionals and loops, but this is not the case with this one.
    + Pleasant for reading.
    + Good examples.
    + Everything in one.
    + Full reference for the standard libraries that come with Ruby.
  2. If you want to get under the surface of Ruby and to have the power to write your own DSLs, the book for you is “Metaprogramming Ruby: Program Like the Ruby Pros”, by Paolo Perrotta. Again the book is published by The Pragmatic Bookshelf. It will teach you the inner doings of the Ruby classes, modules and methods. It will be easier to you to get into how things are implemented in frameworks like Rails.
    + Gives you the information you need on iterations.
    + Cool story :)
    + Advanced but enjoyable.
  3. This article – http://blog.jcoglan.com/2013/05/08/how-ruby-method-dispatch-works is on the same topic as the above book. If you don’t like books, I recommend it, if you like books and read the above one, I still recommend it. It is a good article and James Coglan, the author re-implemented Ruby’s method dispatch in Javascript and in Ruby. This link was given to me by Gudata.
  4. I just love The Pragmatic Bookshelf’s books. I wanted to give you links to books from another  publisher here, but I can’t. Everything you need is on their bookshelf.  “Working with Unix Processes” and “Working with TCP Sockets” are two books by Jesse Storimer. They are very practical and some very important knowledge is provided to you in the form of Ruby code.
  5. Very important place is http://ruby-doc.org. It is self-explanatory.
  6. Another link of interest is https://www.ruby-toolbox.com. It compares the shares of use of different frameworks and libraries grouped by their purpose.
  7. http://www.ruby-lang.org/en

This post is only useful links, so no useful links here… I think it is a good idea to write such posts. There will be post about rails books and links and maybe REST, Vim, Ruby Web… Who knows.

Ruby Bundler : A Source Full Of Gems

TL;DR : Bundler tracks your application’s code and the gems it needs to run, so that the application will always have the exact gems (and versions) that it needs to run. Add the Gemfile.lock generated by Bundler to version control. Bundler’s home is http://gembundler.com.

We know how to install and manage our rubies, and we know how to install and store our gems. The one thing left is how to manage them. The tool for that is Bundler.
It gives you the power to manage your gems per-project. For example Rails uses Bundler to manage the libraries used by an application. You can put your gem configurations under source control and that way all the developers will work in the same environment, with the same versions of the gems. If you remember my article about portable Vim, the idea for the VundleFile is influenced by Bundler’s Gemfiles.

Now is time to install Bundler:

gem install bundler

If we use Rbenv we should rehash… Now you can create a sample Ruby project for example something like:

mkdir -p ~/development/ruby/project
cd development/ruby/project
mkdir lib
mkdir spec

Your source code will be in ‘lib’, your specs will be in ‘spec’ (If you don’t know what is a spec, you will be very happy to find out here).

If we want Bundler to manage the gems for our application we can create a file called Gemfile or execute

bundle init

which will generate it for us.

The Gemfile lists the gems used by our projects. A Gemfile contains one or more sources:

source :rubygems
source 'http://rubygems.org'
source :rubyforge
source 'http://gems.rubyforge.org'

These sources point to the gem servers which will be used to download the gems for the project. If you ran ‘bundle init’, you already have the rubygems.org source.

If you have at least one source, you can add the gems needed by your project. You can:

  1. Depend on gems from the source servers, listing only their names.

    gem 'rspec'
  2. Depend on given gem versions or version ranges.
    See http://docs.rubygems.org/read/chapter/16#page74 or more information. You should read about ‘~>’ if it is new for you.

    gem 'rails', '4.0.0.rc1'
    gem 'rack',  '>=1.0'
    gem 'thin',  '~>1.1'
  3. Depend on a gems located in a Git repositories. You can specify revisions, tags and branches.
    gem 'nokogiri', :git => 'git://github.com/tenderlove/nokogiri.git'
  4. Depend on gems downloaded locally or written by you.
    gem 'nokogiri', :path => 'gems/nokogiri'

You can specify the Ruby versions your project is compatible with:

ruby '1.9.3'

And you can create gem groups. For example:

# These gems are in the :default group
gem 'nokogiri'
gem 'sinatra'

gem 'wirble', :group => :development

group :test do
  gem 'faker'
  gem 'rspec'
end

group :test, :development do
  gem 'capybara'
  gem 'rspec-rails'
endgem 'cucumber', :group => [:cucumber, :test]

This way, for example, gems needed by the specs will be required only when you run Rspec, gems needed by the production will be required only on the production server, etc…

For more about Gemfiles – http://gembundler.com/v1.3/gemfile.html.

Now if you run:

bundle install

or just:

bundle

All the gems listed in the Gemfile will be downloaded and will be available to your project. A special Gemfile.lock will be generated. This Gemfile.lock is very important. You must add it to version control! Be aware that Bundler downloads the gems listed in the Gemfile and their dependencies. By default they are downloaded in your current ruby installation folder’s ‘gems‘ sub-folder.
The Gemfile.lock contains the dependencies and the exact versions of the downloaded gems.
Next time you run the ‘bundle install‘ command this file will be used by Bundler to decide which versions should be downloaded.
Think about it… When you wrote your code, you listed rack as gem without specifying its version. The version of rack was 1.0 at the time, but now it is 2.3 (for example). The current version’s code is very different and your code is not compatible with it. But if you checkout your project somewhere and the Gemfile.lock is in it, Bundler will download rack version 1.0, because this is the version in the Gemfile.lock, the version that was the newest when you first run ‘bundle install‘.
If you wan to update the Gemfile.lock to include the newest versions, there is ‘bundle update‘ command. I’m not going to talk about it now, but do not update Gemfile.lock manually!

So this is Bundler, you and your collaborators will work with the same ruby version and the same gems and gem versions. This way the project is set-upped to work everywhere. When your friends checkout the project and run ‘bundle install‘, everything will be downloaded and configured.

I can continue talking about installing gems contained only in given group, or installing gems in your project’s path, but I think the post is long enough.

You can require your all the gems from your Gemfile or different groups using:

Bundler.require(:default, [:<group_name>, [<more_groups>]])

There is a Bundle.setup method too which adds your gems to the load paths and then you can require them manually. But more about that some rainy day.

Useful Links:

  1. Bundler’s site – http://gembundler.com
  2. Bundle.setup vs Bundle.require, a topic I didn’t cover – http://anti-pattern.com/bundler-setup-vs-bundler-require
  3. About Bundle.install – http://gembundler.com/v1.3/man/bundle-install.1.html
  4. How to use Bundle.update – http://ilikestuffblog.com/2012/07/01/you-should-update-one-gem-at-a-time-with-bundler-heres-how

Ruby Gems : Lucy In The Sky With Gems

Python has its eggs, Java has its jars and ruby has its gems. So a gem is a ruby package, containing some library or executable program. In the previous two chapters about RVM and Rbenv I installed rails using the gem command. Since ruby 1.9, Ruby Gems comes with ruby. So, how to use it?

  1. You can list all the available gems, hosted on RubyGems.org with:

    gem query --remote (gem q -r)
    or
    gem list -r


  2. You can search for remote gems with:
    gem query --remote --name-matches <name>
    or
    gem search -r <name>
    or
    gem search <name>
    or
    gem sea <name>
  3. You can install a gem using:
    gem install --remote <name>
    or
    gem install <name>
    or
    gem ins <name>
  4. You can install a given version of a gem using:
    gem install --remote <name> --version <version>
    or
    gem install <name> --version <version>
    or
    gem ins <name> --version <version>
    or like that
    gem install <name>-<version>

    For versions you can use  operators :

    gem install <name> --version "= 0.1.3"  
    
    All operators:
      =  Equals version
      != Not equal to version
      >  Greater than version
      <  Less than version
      >= Greater than or equal to
      <= Less than or equal to
      ~> Approximately greater than 

    To see all available versions of a gems:

    gem search -a <name>
    or
    gem list -r -a
  5. To see the locally installed gems:
    gem list (-l)
    or
    gem query -l (--local)

    To search in the locally installed gems for given gem:

    gem search -l <name>

    A detailed information for an installed gem:

    gem specification <name>

    This can be executed with the ‘-r’ option for remote gem.
    A cool feature is to run

    gem server

    And to use your browser, opening http://localhost:8808 to browse detailed information for your installed gems.

  6. To uninstall a gem:
    gem uninstall <name>
  7. You can install gems with options like ‘–no-rdoc or ‘no-ri’, see all available using:
    gem help install

    You can put a .gemrc file in your home with some commands and settings to be used with Ruby Gems. The file should look like this:

      gem:  --local --no-rdoc --run-tests
      gempath:
        - /usr/share/rubygems
        - /home/meddle/.stuff

    Read for more here http://docs.rubygems.org/read/chapter/11

I think this is a good manual for the tool, we will use it a lot in the up-coming posts.

Useful Links:

  1. Ruby Gems site – http://rubygems.org
  2. Ruby Gems docs – http://docs.rubygems.org
  3. Manual at http://www.ruby-lang.org – http://www.ruby-lang.org/en/libraries