Deivinson Tejeda

A blog for programmers.

about me

I’m full stack software developer passionate for new technologies and interested in learn new stuff.

How I Have Learnt EmberJS

Since two months I come using EmberJS full. We decided to use EmberJS without strong experience and knowledge. We might use another MV JS framework out there, but We are convinced that using a MV JS framework is the right path to follow in order to avoid have a bunch of JS code unmaintainable.

Besides the kind of app we are developing EmberJS made a perfect match for us.

When I’m into any technology, I follow closely the info stream about it. Yesterday I read this tweet:

Looking to use some Christmas money on #EmberJS learning material. Any recommendations? cc: @tomdale @wycats

That tweet made me think about how I have learnt EmberJS, which is unusual due to way how EmbjerJS is being developed.

EmberJS team core follows an aggressive development strategy until the next release, which consists on every six weeks a new stable version of EmberJS.

When you are trying to learn something new for a real project, often you get books, screencast, blog posts and so on in order to ramp up quickly. The problem here EmberJS with its development model tends to get out of date these resources as quick as six-weeks.

So, You can buy amazing books, read incredible tutorials, watch helpful screenshot, but they might going out of date on next release of EmberJS, definitely that’s not good. It’s very frustrating :–(.

What we did a custom algorithm to sort out this one in order to get good books for reference and get in touch with the official doc.

Might you asking yourself, how works this?

Well, We wanted to have good books with very recent date, in which we get reference to understand more in deep core concepts behind EmberJS and official doc to check out if the book, tutorial, etc is up-to-date. By this way We can take advantage the power of any OSS, its Community.

EmberJS is a good framework with amazing community, besides the core team are guys which know a lot of about OSS.

If you are interested on using Ember JS on your projects keep in mind its development life cycle and when you want to buy or read resource check out the release date and version used. There are many projects out there using EmberJS for real and not just tutorials.

We are using it for real and so far so good.

written in emberjs, javascript

Concurrencia != Paralelismo

Hace días los amigos de la escuelaweb publicaron un buen articulo relacionado con los lenguages scripting mas populares (o menos peores) del mercado en dicho post se hacia una buena descripción de cada uno, mostrando sus casos de uso, pros y contras, si aun no lo leen le recomiendo que lo hagan.

Sin embargo encontré referencia a un termino usado y que puede generar algo de confusión, entiendo también que el post fue creado para un publico menos tecnico y quizas entrar en detalles no era necesario. Acá trataré de aclarar el punto en termas bien práctico.

Concurrencia != Paralelismo, son dos formas como se ejecuta el código en principio todos los lenguajes mencionado en dicho post soportan Concurrencia.

Empecemos con una pregunta simple:

Multiples hilos (Threads) van a ejecutar mi código en paralelo?

Esta pregunta esta mal formulada e interpretada por quien la formula. De hecho se pudiera dividir en dos posible preguntas mas adecuadas.

1) Multiples hilos (threads) pueden ejecutar mi código concurrentemente? Definitivamente Si.

2) Multiples hilos (threads) pueden ejecutar mi código en paralelo? Quizás.

Ahora veamos un poco mas a fondo lo anterior. Dado que somos desarrolladores voy a usar un ejemplo de referencia donde nosotros somos los CPU :).

Un Ejemplo

Imagina tu eres un desarrollador trabajando para una pequeña compañíay dicha compañia tiene dos proyectos, lo vamos a llamar A y B. Ambos necesitan ser completados y requieren un día completo de un desarrollador. Hay al menos 3 formas de lograr este objetivo.

1) Tu terminas el proyecto A hoy y el proyecto B mañana.

2) Tu trabajas en la mañana en el proyecto A, luego te cambias al proyecto B en la tarde. Repites esto mismo mañana y ambos proyectos estarán listo en dos días.

3) El último y mas actractivo es que la empresa contrate a otro desarrollador. Tu trabajas en el proyecto A y Él trabaja en el proyecto B, al final del primer día ambos proyectos estarán listos.

Veamos como actuan los escenarios anteriores en un esquema de concurrencia y paralelismo.

La primera opción representa la forma común como se ejecuta un código en single-thread, dada dos tareas va a ejecutar una y cuando termine ejecuta la otra.

La segunda opción es como se ejecuta un código concurrentemente, multiples hilos (multi-thread) ejecutando código en un solo (y único) CPU. Dada las dos tareas pueden ejecutarlas al mismo tiempo. Tomando este ejemplo tenemos un desarrollador ó CPU y las tareas compiten por tener acceso a dicho recurso valioso :) en el caso de no logran acceso deben esperar.

En otras palabras este escenario representa concurrencia y multi-threaded código no significa que el código va a ejecutarse mucho mas rápido que un single-thread. En todo caso, las tareas siempre se van a completar en el mismo tiempo (Dos días).

Ahora el tercer escenario representa Paralelismo, es decir multi-threaded código ejecutandose en multiples core CPU. Dada las dos tareas ambas se ejecutan de forma simultánea completandose en la mitad del tiempo (1 día).

En resumen el caso #1 y #2 ejecutan código concurremente pero el #3 en Paralelo.

No puedes garantizar que todo será Paralelo.

Para terminar, vamos ilustrar un caso que tu código puede ser ejecutado Concurrentemente sin ser Paralelo necesariamente. Lo único que tu puedes hacer es organizar tu código para ser Concurrente, usando multiples threads. Pero hacer que se ejecute de forma paralela esta fuera de tu alcance, porque esa responsabilidad es dejada al thread scheduler.

Por ejemplo si tú código esta siendo ejecutado ó corriendo en 4-core CPU, y tu haces spawn de 4 threads, es posible aunque poco probable, que tú código sea ejecutado en solo un CPU. Esto porque el thread scheduler decidió agendarlo a un CPU.

written in concurrencia, opinión, paralelismo

Using Ruby Geocoder Gem Locally

These days I have been needing test a small feature (for a personal project) related with Geolocalization. The first and most obvious option was used Geocoder which has a number features enough for what I’m needing.

Alright I already have settled the gem on my Gemfile, but How I can test this gem on my local environment? due to in the docs it’s clear when you use this Gem with a IP 0.0.0.0 the Geocoder::Result object is nil.

Fortunately there is a option at least I can figure out this one in order to sort out the previous issue and do test on local.

We’re going to use Rack middleware in order to mock the IP with a custom one.

Let’s create a file which we called it fake_ip.rb with following content.

1
2
3
4
5
6
7
8
9
10
11
12
13
class FakeIp
  def initialize(app, ip)
    @app = app
    @ip = ip
  end

  def call(env)
    env['HTTP_X_FORWARDED_FOR'] = nil
    env['REMOTE_ADDR'] = env['action_dispatch.remote_ip'] = @ip
    @status, @headers, @response = @app.call(env)
    [@status, @headers, @response]
  end
end

The previous code is pretty simple, the interesting part is on call method which change the values for some of elements env.

In terms very simple The env variable is a hash. That hash contains a lot of useful information including request headers and body, as well as run-time environment data that may have been added by upstream middleware.

Now, edit config/application.rb and put:

1
config.middleware.use('FakeIp', '187.16.144.141')

The previous code allow us to mock the IP with someone custom. Now if you visit a controller a inspect the content

1
2
puts request.location.country_code
# should see the country code for IP 187.16.144.141 BR

I wrote a small rack-app in order to show you the whole workflow.

Do you know a better way to do this? Share it!

written in development, gems, geocoder, rails, ruby

JRuby Bug Fixed With Regexp Class

I have had some days funny playing with JRuby, specifically I’m working in a DSL verbal_expressions to parser URL.

verbal_expressions is so sexy, very verbose as way it was built and as you can use it. I tested it in MRI and works fine, but in my current project, we need developing a set new features upon JVM, by this reason JRuby plays an important role.

When I made tests using JRuby, I found an weird behaviour, assuming that JRuby allow carry (almost) the whole Ruby code wrote using MRI.

Basically, I made the following code.

1
2
3
4
5
6
7
8
9
class Foo < Regexp
  def initialize(&block)
    instance_eval &block
    super('/some_regex/')
  end
  def some_method(value)
    puts "Output: #{value}"
  end
end

Because I went to use the previous code just like this.

1
Foo.new { some_method 'Hi!' }

As you can see is very simple what I want, just inherit from Regexp, nothing out of usual here. But when I ran the previous code get the following output.

1
2
3
4
5
6
7
8
9
ArgumentError: block not supplied
    from org/jruby/RubyBasicObject.java:1709:in instance_eval'
</span><span class='line'>    from (irb):10:ininitialize’
    from org/jruby/RubyRegexp.java:729:in new'
</span><span class='line'>    from (irb):17:inevaluate’
    from org/jruby/RubyKernel.java:1066:in eval'
</span><span class='line'>    from org/jruby/RubyKernel.java:1409:inloop’
    from org/jruby/RubyKernel.java:1174:in catch'
</span><span class='line'>    from org/jruby/RubyKernel.java:1174:incatch’

With idea to discard some problem in my code I decided test it with a dummy code like follow:

1
2
3
4
5
class Dummy
  def initialize(&block)
    instance_eval &block
  end
end

When I run the previous code:

1
2
>> Dummy.new { puts “yay #{self.inspect}” }
yay #<Dummy:0x54bbb2d0>

Works as expected. In JRuby’s IRC I explained the previous ones, after ratnikov made the tests, he confirms it was an issue in RubyRegexp implementation.

Basically, RubyRegexp was ignoring the new’s block

written in bug, fixed, jruby

What’s #painpoint in JRuby?

Yesterday from jruby’s twitter account started a thread related with biggest pain point when users using jruby. Now, I’m getting started to work with jruby, basically combined with Hadoop. I think is very interesting this thread.

written in jruby, painpoint Read on →

Getting Started - Again

Has been a year with many changes, the most important (I think) was get out of my country. Now I’m living in Santiago Chile, a beatiful country that received me. A year later, still I’m learning so many stuff about inmigration life.

I lost all my previous posts :–( (although anyone read it)

I hope to write a bit more with main idea to leave this blog like a repositories of notes.

written