Know how to CRUD

While there are some similarities to Rails, there a few differences to keep in mind when performing CRUD operations in Ember. Let’s compare creating, updating and deleting a user in both frameworks.

Creating a new User instance:

In Rails:  app/controllers/users_controller.rb:

Screen Shot 2015-11-24 at 8.26.16 PM

In Ember:  # app/routes/users/new.js:

Screen Shot 2015-11-24 at 8.27.47 PM

In both cases, we create a new instance of a User, but do not persist it. Persisting records to the database (or API) has some differences. In Rails we add a create action, create a new instance based on parameters that were passed, and then call save on it.

In Ember, we only need to add an action to our users/new route that saves the User record we’re currently working with.

In Rails: # app/controllers/users_controller.rb:

Screen Shot 2015-11-24 at 8.32.32 PM

In Ember: #app/routes/users/new.js:

Screen Shot 2015-11-24 at 8.34.11 PM

Updating user attributes:

user.setProperties({ firstName: ‘Tatsiana’, lastName: ‘Borshch’ });

One key difference between Rails update_attributes and Ember setProperties is that update_attributes will automatically persist the record to the database, while setProperties  will update the record immediately on the client but not attempt to save it. We can verify this by checking the isDirty property, which is equivalent to the changed? method in Rails. To actually save the record in Ember, we need to call save. Ember will make a PUT request to the API to persist the changes.

Deleting a user:

To delete a record in Rails the destroy method is used. In Ember, the equivalent function is destroyRecord, which marks a record as deleted and immediately calls save on it. In case the destroy fails, it is a good idea to use catch along with reload to refresh the state of the model from the server.

Screen Shot 2015-11-24 at 8.51.40 PM

Ember models also have a function called deleteRecord. Like destroyRecord, the record will be marked as deleted. The difference is that save will not be called afterwards.

Must have Development Gems to install on every project!

    Have you wasted a few hours debugging some condition only to find a query or function something was returning nil? Spent time optimizing queries only to forget to do eager loading? Scrolled through your development log past 100s of lines for requests for images, css and javascript that you don’t really need to refer? We have all been there and these gems solve exactly these problems. Once you learn how to use them you’ll find that you can accomplish what sometimes takes hours in minutes.

      One of the largest portions of time that you will spend developing an application is on debugging and optimizing. As the rails application becomes bigger with more moving parts, debugging it becomes slower and finding parts that are causing your application to be slow become fewer in between.

Awesome Print

Rails objects can get pretty dense and hard to read when inspecting in the console. Awesome print solves this problem by prettifying the output. Read on to see by what I mean.

Lets run the command User.first in the rails console. This is something most of us do on a day to day basis in the rails console.

Screen Shot 2015-11-04 at 11.17.30 PM

As you can see on the Terminal above, the output is kind of hard to read although the object is not that complex. Awesome print takes that output it and makes it much easier to read. Lets install the gem and see how it changes.

Use gem “awesome_print”, require:“ap”. Make sure to include do bundle install and restart the rails console. It will not work without it.

We run the same command, however this time we just run the command by adding ap to the beginning of the commend. So it becomes ap User.first. Basically, what you are doing is passing to the ap method the object that you want it to print.

Screen Shot 2015-11-04 at 11.15.59 PM

Screen Shot 2015-11-04 at 11.14.46 PM

Screen Shot 2015-11-04 at 11.24.47 PM

Screen Shot 2015-11-05 at 12.55.53 PM

Rails Panel

Rails panels adds a number of useful features to the Google Chrome inspector. To use this you will need to install the  meta_request gem and also install the Chrome extension by going here.

Rails panel is something I keep switched on pretty much all the time if I’m doing any backend work. It gives you all the metrics and information required without actually having to go into the Rails console.

The first columns gives you the HTTP Response Status, the Controller and Action that your route hit, the HTTP Verb (PUT/POST/GET), request format (HTML, JSON, XML) and the response time. These metrics by itself would have been quite valuable.  

I find the ActiveRecord tab to be extremely useful as it gives you the raw SQL queries being executed and the executing time for that query. It also gives you the number of queries that were used for that request which is great for optimizing the app. Apart from that, clicking on the controller name automatically opens your editor and takes you to that line of code!

The next tab is the Rendering which gives a breakdown of all the views being rendered. This is useful for finding which partials are taking the longest to render. Click on the view name automatically opens it in your editor.

Quiet Assets

Do your rails server log look like this? Filled with asset requests that you don’t really need to see, making you scroll endlessly to find the last request? My biggest annoyance would be that while scrolling I would more often than not miss the relevant request.

Quiet Assets as it names suggests removes all the asset requests from your rails console so you can see just the relevant request data. Installation is as simple as dropping gem 'quiet_assets', group: :development into your gemfile and bundling. You should see something to the screenshot below.

HOW DO I BENCHMARK RUBY CODE?

HOW DO I BENCHMARK RUBY CODE?

So you’ve got some Ruby code and you want to make it faster. Maybe, you’ve already got a new implementation in mind, or maybe you are still cooking that up. But how do you make certain that your new implementation is faster?

Getting started

The Benchmark module is in the standard library, so you do not need to install any gems to get it.The Benchmark module provides methods to measure and report the time used to execute Ruby code. The Benchmark module offers several different ways for you to benchmark your code. I’ll take you through the different options and their use cases. The simplest way to measure your Ruby code is with Benchmark.measure. It returns the time used to execute the given block.

Screen Shot 2015-10-21 at 6.19.34 AM

This will return something that looks like this:

Screen Shot 2015-10-21 at 6.20.24 AM

With no context, these might look like magic numbers. Here’s what they mean:

                         Screen Shot 2015-10-21 at 5.46.11 AMScreen Shot 2015-10-21 at 5.41.35 AM

This report shows the user CPU time, system CPU time, the sum of the user and system CPU times, and the elapsed real time. The unit of time is seconds.

Generally, the number farthest to the right is the most important one. It tells how long it actually took to perform the operation. If you are curious about why the clock time is so high, the other numbers can help you drill down to see if you are spending time in system functions or your own code.

Now that you know what those magic numbers mean, we can move on to the core Benchmark API. The truth is that I rarely use the measure method on its own. It only prints the benchmark for a single block of code. The most common way to use Benchmark is to compare the execution time of different approaches to the same problem. Benchmark has some built-in methods for this exact purpose.

Benchmark #bm

This method lets you define several blocks of code to benchmark, then prints the results side-by-side in the same format you saw earlier.

Screen Shot 2015-10-20 at 12.58.20 PM

Screen Shot 2015-10-20 at 1.02.01 PM

You call the Benchmark#bm method passing a block. The block variable is a special object provided by Benchmark. It gives you a report method that you call with the block of code that you want to measure. Benchmark then runs both blocks of code and prints their execution times side-by-side.

Often, when doing benchmarks that test code that executes very quickly, you need to do many iterations to see a meaningful number. In this case, I did 100,000 iterations of each variant just to get the execution time up to half a second so I could grasp the difference.

Labels

In this benchmark, I buried some comments in the source that said what each block of code was doing. That is not so helpful when looking at the results! Benchmark allows you to pass in a label to the report method that will be printed along with the results.I have now removed the comments describing the blocks and pass them in to the report method as an argument. Now the output describes itself. Make sure you pass a value thats greater than the length of your longest label. Thats the happy path.

Screen Shot 2015-10-20 at 11.18.39 PM

Screen Shot 2015-10-20 at 11.27.30 PM

Benchmark#bmbm

The Benchmark#bm you just saw is really the core of Benchmark, but there is one more method I should mention: Benchmark#bmbm. Thats right its the same method name, repeated twice. Sometimes, with a benchmark that creates a lot of objects, the results start to get skewed because of interactions with Ruby’s memory allocation or garbage collection routines. When creating a lot of objects, one block may need to run garbage collector, while the other does not; or just one block may get stuck with the cost of allocating more memory for Ruby to use. In this case, the benchmark can produce unbalanced results. This is when you want to use Benchmark#bmbm.The method name is suitable because it actually benchmarks your blocks of code twice. First, it runs the code as a rehearsal to force any initialization that needs to happen, then it forces the GC(Garbage Collection) to run, then it runs the benchmark again for real. This ensures that the system is fully initialized and the benchmark is fair.

This last example benchmark allocates a lot of objects. When this runs at the rehearsal stage, Ruby has to allocate more memory to make room for all the objects. Then when the ‘real benchmark happens, the memory is already available and just the actual implementation is tested.

Screen Shot 2015-10-20 at 11.33.10 PM

Screen Shot 2015-10-20 at 11.34.19 PM

Notice the discrepancy between the rehearsal and the benchmark! Thanks bmbm!

Conclusion

When you want to try your hand at speeding up some of your Ruby code, make sure that you measure, measure, measure to prove that your new implementation is faster than the old one. This great little benchmarking library ships with Ruby right in the standard library, so theres no excuses!