A couple of things about the $scope in AngularJS

The idea of scope, or rather $scope, always produces conflicting feelings when I work with AngularJS . It is a very clear concept but at the same time it has an abstract touch that sometimes seems to slip between the neurons, so it seemed a good idea to spend some time writing (to myself) this mental note for the next day that I face the köan that this idea means to me

What is the scope and what is it for?

The scope is the glue between the view and the controller. It is that object that carries with it the methods and properties that we can apply in the view and / or in the controller.

 

¿How does the scope works?

The idea sounds great but everything starts to get complicated when you roll up your sleeves and start digging into code so I’ll try to explain it with an example.

Let’s start with the view. A simple html but with a little dressing:

 

Inside the body tag we can find two nested divs with it’s angular directives. With the first one, ng-app, we define which module is “responsibly” of this element of the DOM and in the nested one (or in the same) we add the ng-controller directive. In this case counterController will be the controller in charge of this div and this is the way we can define the scope of the view.

vemos tenemos dos divs cada uno con su directiva de angular. Con ng-app definimos que modulo es “responsable” de este elemento del DOM y en un elemento anidado (o en el mismo) añadimos la directiva ng-controller. En este caso counterController será el controlador responsable de ese div y así definimos el scope en la vista. Let’s say that all that remains inside the element labeled with the ng-controller directive will be the scope for that controller.

 

And here is our module and our controller. The controller must always receive, at least, $scope. Here I must precede with $scope. all the properties and functions that I want to be accessible from the view. For example, the counter variable that is in the view. In the controller is preceded by $scope. same as the startCounter method.

In contrast, the timer variable or the updateCounter function are only used inside the controller and therefore it is not necessary to add any type of prefix outside of the JavaScript standars.

 

 

Shared scope via module

This is a short entry but I am pretty sure that I’ll be reviewing this post soon or latter because I find myself trying to avoid repeating scopes every now and then.

And the solution is as easy as moving the scope to a concern:

And include it in the models as needed:

So now we can write:

Note to myself: Just remember to respect the naming conventions about concerns and the use of the past tense in the module when writing “included”.

Day 1 of 100. My journey through the #100DaysOfCode Challenge

‘Try to leave this world a little better than you found it’

Robert Baden Powell

After I committed to the challenge I wasn’t very sure about where to start. As I said in my previous post I’ve a lot of reason to start and a lot of reason translates into a lot of choices but I didn’t want to get stuck with my indecision and  choose to keep it simple, so I started working today refactoring an assignment that I already published on mi github profile.

The original assignment was part of the hiring process of a British company called Reedsy. Making the long story short my code wasn’t what they were expecting but I say it with no hard filings, they were very nice and took the time to send me some feed back about my code, so I can improve my skills as developer.

All this feedback went directly to a trello card in my to do list until today when I decided to use it as a starting point to develop a basic Rails 5 app where I can apply some patterns and best practices starting with some refactor.

Let’s see where this takes us.

4 reasons to start the #100DaysOfCode

For some time now I have been thinking about participating in this “challenge”. I’ve been dealing with code for about 10 years and sometimes it might seem that this type of initiative is aimed exclusively at people who want to start programming but the reality is that I can think of a few reasons to be excited about this:

1- Get in your own code:

The first and most important is that I do not usually find time for my own code.

developer’s weekend

All the programmers are exposed to ideas and projects that end up stimulating that little entrepreneur that we all have inside. Either to finish launching our own startup or simply to practice with new technologies. The point is that I have never met a developer who did not have at least one project in mind that he would like to dedicate some time to. In my case the problem is to choose one of the many and very diverse (and crazy) ideas and find the necessary time to start it and I thought that committing to finish this challenge can help me create the habit of dedicating time to my own code.

2- Learn something new every day:

Another really important reason is to keep learning. Many times I find myself saving for later very interesting information that I could apply in my code but since I do not have time to investigate and experiment I end up saving the situation with the tools that I already have and that is without a doubt a big mistake in which the developers with some experience usually fall.

Having certain tools and resources that have allowed you to open up to where you are now is fine, but it should not be a reason to rest on your laurels and stop learning.

There are few labor sectors in which the need to stay updated is as pressing as in software development and if you are not willing to spend some time each day learning new things perhaps you should consider swinging to a more traditional profession.

 

3- Unify and consolidate knowledge:

It’s weird the day I do not stumble on a new Ruby method that makes my day happy or a new way to complicate my life with asynchronous behaviors in any JavaScripts framework.

But sometimes I have the feeling that all that knowledge is scattered through the limb and I do not find an opportunity to unify all those little tips, patterns and programming paradigms that appear in the different tabs of my browser as I search for a solution specific to my problem of the day.

The challenge proposed by # 100DaysOfCode gives me the opportunity to expand with these discoveries, connecting the points, forcing me to go beyond the quick solution looking for scenarios in which to apply this parked knowledge.

4- Contribute to OpenSource:

This is my great unresolved issue and I could write a considerably long post with all the reasons why I want to contribute in the opensource community so here I will limit myself to briefly explain how the challenge of # 100DaysOfCode can help me achieve it.

My biggest problem when participating in a public repository is time.

No matter what your level as a developer is, if you want to start contributing to a public project you will have to invest a lot of time in understanding how the community works, how they communicate and make decisions, how bugs are assigned and the priorities, how the pull request process works or simply how you can install the code locally and put it to work in your development environment.

All this requires a time that you have to invest voluntarily and what better exercise than committing yourself to devote at least one hour a day to coding to acquire this habit?

 

 

 

Refactor from scratch

working with legacy code on Ruby On Rails.

This week I have dedicated some time to one of those tasks that I always have in my mind but nobody never ask you to spend time until it is too late.

In production we have a controller that has been neglected and has become fat. Our app follows the MVC model and the ideal in these cases is to follow the rule of having controllers as few as possible and leave the full weight of logic within the model.

I must confess that, in the beginning the code of the controller was very simple and only was supposed to retrieve the conversations, but little by little, we added new tasks of what we call “easy ones” and the thing has gone wild.

 

First of all it is important to define what the controller is doing:

  • Check that the current user is not the admin and if it is, it returns an error message.
    • If it is not the admin:
    • checks if the params[:users] exists and if exists adds it as a parameter to the action that we use to get the conversation’s list.
    • Applies pagination to this list.
    • If the layout should be the new one and the parameter params[:new_layout] exists adds to the json response a new field named is_new_count with an integer corresponding to the number of new conversations.
    • In other case adds to the json response the result of c.patient.formated_answers.

The first step is to move all the actions inside the controller to external actions, in this case private methods of the controller, which I will call from the index.

My plan is that these actions will be responsible only for calling model methods.

At the time of testing I will start with the methods of the model and then checking that the actions of the controller call those methods.

Models

In the user model I have defined this method:

There is a part of the code that handles patients_emails. This is part of a filter that is no longer used so it can be removed from the code leaving to the method the only task to check the role of the current user and apply the scope where_last_message_is_not_nil on the collection of conversations of this user.

This is the test code for the scope:

Y este el test para el método conversations_as_current_user:

 

The next method to be tested will be new_conversations_count that links the previous method with two scopes and returns the number of elements in the collection:

Eston son los dos scopes:

Y estos los tests para los dos scopes:

Once the scopes have been tested, the method test only has to ensure that the call to the 2 scopes is linked to the collection provided by conversations_as_current_user:

 

Controller

I move all the query logic to get the list of conversations according to the role of the user and the layout that uses to a private method outside of the main controller:

Y hago lo mismo con lógica que comprueba si estamos en la última pagina, consulta el numero de conversaciones nuevas y el proceso que da formato a la info relativa a las conversaciones que queremos enviar en nuestro json:

Leaving us with a controller much easier to read and that only takes care of calling different methods:

In the testing of the controllers we only have to worry about the index calling each of the methods but this is another story and as this post has been really long I will leave this question for another post.