Adding organization repos to Travis-CI: Part I

It was a nice FridayPorras and I were at the BeBanjOffice and  we were working on adding organization support to Travis-CI.

First, we needed to find where the user repos were being fetch. Said and done, we found that travis is using the ServiceHookController to ask the server for repos (and to update them too, but don’t hurry, we’ll get there in part II). The controller was using the github_repositories method in the User model. Finally, we arrived to Travis::GithubApi, where all our questions found answers.

repositories_for_user just relied on Octokit#repositories for getting the repos, so we added all the code after the plus sign. You might think that this code lacks the proper security, is wrong and that it shouldn’t be there (and damn it, you’re right!) but there is no easy way to retrieve only the repos where the user has admin privileges (we wasted hours on this and a quick message to Github confirmed it).  Basically, it asks for all organizations for the given user (beware! You need to make your membership public, otherwise it won’t work) and then flat_map them to the repos in the given organization (whether the user can administrate them or not).

Later, the each block was added so we could know whether the repo belongs to the user or to an organization.

Stop! Hammertime!

We needed a way to let the user know that a repo actually belongs to an organization, so we added that info to the template (that {{#if content.organization_name}} is ours :D) and added some style so it could look this awesome:

Travis CI - Distributed build platform for the open source community

We had some tough time trying to get it vertically centered, but after realizing that Github has its tags the same way as we do, we stop trying to fix it. And they still look awesome.

More coming in part II.

Writing your own JRuby extension. Part II: Creating your first class.

More Mormon Matryoshki
What’s the point of coding a JRuby extension if you don’t create classes? Well, I cannot think of any case, but if you find one, please, let me know.

Do you remember Java’s classes hierarchy? If so, you’ll realize  that Java objects inherit from java.lang.Object by default but that is not actually what we need. But how can we tell JRuby that our object inherits from Object, the king of Ruby world? The answer is so simple: just extend RubyObject! (There is a RubyBasicObject too) Taken from Nokogiri::XML::Node:

Of course, you can extend any other class, as long as it is a “Ruby object”. For example, Nokogiri::XML::Document extends from Nokogiri::XML::Node, and we do not need to do anything special to reflect it, just extend XmlNode like XmlDocument does:

After talking a bit about hierarchy, let’s talk about Java constructors. At least two parameters are needed: a org.jruby.Ruby object and a org.jruby.RubyClass object. Being the importance of the former quite obvious, the reason for the latter may not be so clear. Let me show you some real world code: Nokogiri::XML::Node’s dup method. Take a look at the following test:

Both new and dup methods in subclass rely on Nokogiri::XML::Node’s. In here, you can see the this snippet of code:

The rb_obj_class method returns the class of an object, in this case, self. This way, the new node will be an instance of the same class as the original node. That’s the reason a RubyClass is needed in the constructor, in order to know which is the actual class being instantiated.

By the way, do not forget to call super with the Ruby and RubyClass objects.

Next step: creating methods.

Creative Commons License photo credit: quinn.anya

Writing your own JRuby extension. First problem.

Denial
Maybe, when requiring your just created extension, you get a LoadError. If it is the first time you require it, it is quite likely that you have not followed JRuby requiring conventions. If you want to know how require works, you can find the best documentation ever about it in the comment before org.jruby.runtime.load.LoadService class.

Creative Commons License photo credit: cesarastudillo

Writing your own JRuby extension. Part I: BasicLibraryService.

Note: not code in this post, but you can see the code in Github. Follow the links!

Writing a JRuby extension is very easy, but there are almost not post out there about it. As far as I know, there is only one, Ola’s. It is a really good tutorial indeed, but it lacks some details that might be not-that-easy to solve. Please, take some time to read it and, if some details are different, do follow Ola’s way.

Everything’s ready now, so let’s start talking about BasicLibraryService. If you take a look at Nokogiri4J sourcecode, in ext/java/nokogiri folder, you will see a NokogiriService.java file. NokogiriService implements BasicLibraryService. This interface consists only of the method basicLoad which receives a Ruby object.

We will use this method to define classes and methods in the Ruby world. For defining a module, defineModule method is used with the name of the module. After that, modules and classes under that module can be defined easily by using the methods defineModuleUnder, which takes the name as parameter, and defineClassUnder, which takes the name and few parameters more. Let’s dive into it.

defineClassUnder needs three arguments. The first one is the class’ name. The second, is the parent class. If you have defined it previously, just passed it,  otherwise use RubyObject by calling the method getObject on the Ruby instance. The third parameter is an ObjectAllocator. ObjectAllocators returns intances of the classes in Java world. When instantiating Nokogiri::XML::Comment in Ruby world, JRuby will ask the ObjectAllocator for an instance of the Java class. It passes a Ruby object and the RubyClass being instantiated to the allocate method in the ObjectAllocator (more on RubyClass in following posts).

Finally, we will need to define some methods. Easiest way is by using the defineAnnotatedMethods. It takes a Java class as parameter. For knowing what this method does, you need to know a bit more about @JRubyMethod annotation (more on it in following post, have you realized the “Part I” in the title?). As you define methods, you may need to undefine some in a subclass. So easy! Use the undefineMethod method, which takes the name of the method as parameter (surprisingly, it undefines a method by redefining it!).

Next time, Implementing your first class.

If you are (un)happy with Ruby 1.8.7

There are two interesting topics in the Ruby Forum being discussed right now. Both opened by George Brown (the guy behind Prawn). They are:

I’ve read every single message because backwards compatibility in Ruby 1.8.7 is something that I do not fully understand. It all started with this comment in Jaime’s blog. There, Jaime wondered if Ubuntu did the right thing by updating Ruby to 1.8.7, even if that version breaks rails (in fact, it did). Well, in this case, my humble opinion was yes, Ubuntu did well by updating Ruby. But now, let’s consider other things.

So far, I’ve seen two kind of complains against Ruby 1.8.7:

  • Coding working in 1.8.6 that doesn’t work in 1.8.7. I’ve been talking James Coglan about it, and the one of the errors was that his code relied on the order of the keys in a hash. But, there are other he hasn’t been able to fix, and is something regarding regular expression. I am unhappy with this kind of “new features”.
  • Other people is complaining about working code in 1.8.7 that does not work in 1.8.6. I really understand them, because they program really cool gems and they have to test if they have used not-valid-1.8.6 code. I wouldn’t care too much about but we must keep in mind that 1.8.7 is a minor release.

Finally, I just want to say that, as many people has pointed out before me, it would be better to migrate to 1.9.1. Common! It has been already released! Anyway, that’s not the point of the discussion. It is all about a minor release with too many changes (I’m not talking about bugfixes). Do I like the new things? Yes, I do (except some that I cannot really understand). Am I happy with Ruby 1.8.7? No, I’m not because it is suppose to be a minor version release and it is making too much noise.

Problem 3

Wording: (Original) The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Solution:
First the code:

include Math
def prime_factors(num, factor=2)
return [] if num <= 1 next_pf = (factor..(sqrt(num).ceil)).find(lambda {num}){ |x| num%x == 0 } return [next_pf] + prime_factors(num/next_pf, next_pf) end puts prime_factors(600851475143).max [/ruby] The code is a direct port from the one in PyEuler. It is based mainly in the idea that the first factor of a number is always prime. Line 3 breaks recursion and line 4 works out the next prime factor (actually, it finds the smallest factor). For doing this, it uses find method. If no element match the criteria, then it returns the number (that is what the lambda block is for). Finally, line 5 merges the results and line 8 print the result. This time just one code is showed.

RMagick4J 0.3.6

I am glad to announce a new version of rmagick4j.

RMagick4J aims to implement the ImageMagick funcionality and the C
portions of RMagick for make it works in JRuby.

Current stable version: 0.3.6
Project URL: http://code.google.com/p/rmagick4j/
Installation: gem install rmagick4j

Google Summer of Code project should be thanked for making this new
release possible.

In release 0.3.6 you can find the next improvements:

  • More Draw primitives (clip-path [creatin a clip-path and using a
    clip-path], fill-rule, rotate, scale [reimplemented], skewX, slewY,
    stroke-linecap, stroke-linejoin, stroke-miterlimit, translate).
  • Solve a bug with transparent stroke and line primitive.
  • Added the following Draw instance methods:
    • annotate
    • get_multiline_type_metrics
  • Solved a bug that caused the background become black while resizing
    images with alpha channel.

Please try out your applications with rmagick4j and help us provide
feedback. It is our goal to make a fully-compatible implementation of
RMagick4j in JRuby.

Sustituyendo a las animadoras con Ruby en Mac.

El título del post puede sonar raro, pero lo que voy a mostrar hoy es cómo conseguir tu propia animadora en Mac con Ruby. Lo que haremos será hacer que nuestro ordenador, con una orden como:


ruby cheerleader.rb Serabe

Nos muestre por pantalla:


Dame una S
Dame una E
Dame una R
Dame una A
Dame una B
Dame una E
SERABE!!!

Además, utilizando el comando say de Mac, nos lo dirá (si queréis que lo grite, subid el volumen al máximo).

Empecemos con el código:

  1. string =  ARGV.join(' ')

Aquí simplemente recogemos los parámetros pasados por consola y los concatenamos con un espacio entre medias. Ahora la parte interesante:

  1. string.each_byte do |b|
  2.   if /[a-zA-Z]/ =~ b.chr
  3.     shout = 'Dame una '+b.chr.upcase
  4.     puts shout
  5.     `say #{shout}`
  6.   end  
  7. end

Para cada letra, una vez comprobado que es una letra y no un espacio, construimos un grito (‘Dame una S’), lo imprimimos por pantalla y hacemos que el comando say lo diga.

Finalmente, con un

  1. puts string.upcase + '!!!'
  2.  
  3. `say #{string}`

Imprimimos la última frase.

Ya habéis visto cómo crearos vuestra propia cheerleader. En próximos episodios veremos cómo añadirle autoregeneración como Claire.

RMagick: Dibujar con patrones

Una interesante cualidad de la clase Draw de RMagick es la posibilidad de definir patrones a través del método pattern.

En primer lugar, lo básico:

  1. require 'rubygems'
  2. require 'RMagick'
  3.  
  4. include Magick

Ahora definamos el patrón. Para ello, necesitamos cinco parámetros, el nombre, dos números que recomiendo ponerlos a cero (después de unas cuantas pruebas, no he notado diferencias notables) y después las dimensiones del patrón.

  1. draw = Draw.new
  2.  
  3. draw.pattern('circles', 0, 0, 10, 10) do
  4.   draw.stroke 'none'
  5.   draw.fill 'red'
  6.   draw.rectangle 0, 0, 10, 10
  7.   draw.stroke 'LightGreen'
  8.   draw.fill 'blue'
  9.   draw.circle 5, 5, 5, 0
  10. end

Ya, por último, dibujamos un cuadrado y lo plasmamos en una imagen de 300×300.

  1. draw.stroke 'circles'
  2. draw.stroke_width 25
  3.  
  4. draw.fill 'none'
  5.  
  6. draw.polygon 150,0, 300,150, 150,300, 0,150
  7.  
  8. img = Image.new 300, 300
  9.  
  10. draw.draw img
  11.  
  12. img.write 'pattern.jpg'

Obteniéndose el siguiente resultado:

Dibujo con patrón como brocha
Dibujo con patrón como brocha