Thursday, November 22, 2012

JQuery and Rails3 Autocomplete

I wanted to do a project with Ruby and Rails and needed some fields to autocomplete. I did a search and found some information, but things didn't seem to work when I followed the instructions.

In the process of debugging, I found some things that are worthwhile, so I want to save them here. For me to remember and possibly for others to save time.

The simplest way to get going with the JQuery based autocomplete on Rails3 is through the use of this tutorial.

The tutorial and sample code is based on Rails 3.0, and I was using 3.2.9 or 3.2.8 on my machines. So I felt brave and updated the Rails version in the project Gemfile to match my installation. ... and things got interesting. Here are some fun facts and steps.
  • Your Rails version by default won't be 3.0.0. More recent installations are 3.2.9.
  • If you install with the more recent version of Rails, the likelihood is that you will get the rails3-jquery-autocomplete gem version 1.0.10. The tutorial asks you to run the following command and that will cause this gem to be installed.
    bundle install
    The reason you are getting 1.0.10 or a higher version is because the tutorial content does not specify a version, and the most recent one is pushed down. However, the tutorial and sample app uses 0.6.0 and that is a problem. So if you are following the tutorial, make sure you make that line read:
  • gem 'rails', '3.0.0'
    gem 'rails3-jquery-autocomplete', '0.6.0'
    gem 'nifty-generators'

  • The tutorial uses a command "rails g autocomplete:install" to generate autocomplete.js file. From what I have read on the blogs and other q&a on StackOverflow, most people seem to think that this is a default Rails functionality or a function of using the autocomplete gem. It is not.
    This won't work if you skip the addition of nifty-generators above. So don't be like me and don't try to cut corners on things you don't know, at least not yet. 

  • It is likely that the JQuery library you are using will be 1.8.2 or later, not 1.4.2, and the JQuery UI will be 1.9.1 or later, not 1.8.4. That is OK. There is no change in the use of these. Make sure however, that your application.html.erb file has the right versions associated with these links and includes. Another to keep in mind here is that the library that you download from JQueryUI site is not going to contain the minimized version of the jquery library. It will have the full version. So make sure your application.html.erb file reflects that. My working version looks like this for <head> element.
        <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
        <%= javascript_include_tag 'jquery-1.8.2.js', 'jquery-ui-1.9.1.custom.min.js', 'autocomplete-rails.js', 'rails.js'  %>    
        <%= javascript_include_tag 'application' %>
        <%= stylesheet_link_tag "application" %>
        <%= stylesheet_link_tag 'jquery-ui-1.9.1.custom.css' %>
        <%= csrf_meta_tag %>
        <%= yield(:head) %>

  • The most important trick comes in the show.html.erb. The tutorial asks that you have code that looks like:
    <%= form_tag do %>
      <%=text_field_tag 'name', '', :autocomplete => welcome_autocomplete_brand_name_path %>
    <% end %>
    That is all good, if you are using the right version of the gem for the tutorial,  0.6.0. However, I found out that 1.0.10 version of this gem does not work with this code and instead it requires the autocomplete_field_tag instead.
    <%= form_tag do %>
      <%=autocomplete_field_tag 'name', '', welcome_autocomplete_brand_name_path %>
    <% end %>
    0.6.0 supports both text_field_tag and autocomplete_field_tag, while the 1.0.10 supports only the latter. Please note the minor format difference in how the two are pointing to the path.
  • If you have changed your gemfile after you ran bundle install command, make sure you run
    bundle update
    This will make sure you have the right and updated gem files.

  • If you are running with a recent Rails version, you will find that a directory named app/assets exists, and is ready to receive your javascript and CSS files after you downloaded them from JQueryUI web site. Use this directory instead of public/javascript and public/stylesheets directories. You won't be able to get things working unless you do this. You will see script file loading errors in the console.

  • Since the recent Rails has automatic inclusion of script and CSS files from the current directories, you don't have to make any changes to your application.js file. I include it in case you have other things included in there, you can see that in the <head> content I listed above.
That's it. This should get the demo to work and allow you to play a little. Have fun !

Wednesday, November 21, 2012

Using SyntaxHighlighter in Blogger

I have been postponing posting code here since I wanted it to be formatted properly and did not have a chance to play with syntax highlighting. There is a nice library that contains css styles and formatting scripts, named just that; here is the site.

To get the highlighter to work, you need to add some script and styles to your blog template. There are nice folks out there who did this work already, you can find one here.

This particular guide and many others tell you to embed the links into the page along with a script tag that enforces the highlighting when the page is loaded. Here is the suggested script snippet that is used in addition to links to CSS and Javascript files.
<script language="javascript" type="text/javascript">
 SyntaxHighlighter.config.bloggerMode = true;

Unfortunately for dynamic view templates like this one on Blogger, it does not work. There is a workaround though, that is to call the highlighter when the page is loaded. The code below highlights anything that has the right class attribute for SyntaxHighlighter library, independent of the name attribute. Which makes it nicer when you have multiple code snippets on a page.
<script type="text/javascript">
  // code snippet is loaded here, highlight everything.
  SyntaxHighlighter.config.bloggerMode = true;

You don't even have to add this to your template. Just make sure you add it to the bottom of your post using the HTML view on Blogger (not the Compose view). As you can see here, it works. It took me some time to discover that the dynamic views are rendered differently. Most instructions before that were irrelevant. Hope you stumble into this note faster than it took me to find this information.

Thursday, August 9, 2012

Hybrid Car: Multi Thousand Dollar Feel Good Donation

Let's do an experiment. How would you answer these questions:

- Donate some money to save the environment. The amount needs to be bigger than $1,000 and may be less than $5,000.  But it has to be in that range. Would you  ?

- Would you be willing to give that donation to an industrial corporation instead of an environmental or nature organization, so they give you tools to be less harmful ?

- What if you could have less negative impact on the environment without giving this amount to a corporation, through change of your behavior over time. And perhaps you could donate the money to a real cause ?

I started to ask these questions and more, when I discovered the differences in prices of hybrid vehicles. At first, I was asking the simple question of how much would I "save" if I purchased a hybrid vehicle. Then, after seeing price differences I started to ask people I know who purchased hybrid vehicles, about what made them buy one. Around that time I listened to a podcast about signalling in economics and its effects on purchase behavior, specifically relating to Toyota Prius owners, which put the "vanity" angle on hybrid vehicle ownership. So I wanted to do some more research.

Here I am sharing the process and results of what I have done while evaluating the topic. As a disclaimer, I am not suggesting that you should or should not buy a hybrid vehicle. I am not suggesting a brand is better or worse than others. Finally, I am not suggesting that you should or should not care about environment and/or spend money to protect it. Hope the content below helps you make decisions that work better for you.

I took Toyota's Prius and Corolla, and Honda's Civic and Civic Hybrid. The prices are from internet from the same site ( so they are consistent among themselves. I also noted the MPG values from the same site, for each model. Average price and average MPG values assume that the same individual would make similar feature choices when buying a car and would drive in a similar way independent of the type of the car.

Brand / Model Price Range Price/Avg MPG MPG/Avg
Toyota-Prius $24,000 - $39,525  $  31,762.50 51/48 49.5
Toyota-Corolla $16,130 - $18,820  $  17,475.00 27/34 30.5
Honda Civic Hybrid $24,200 - $26,900  $  25,550.00 44/44 44.0
Honda Civic $15,755 - $27,805  $  21,780.00 28/36 32.0

At first glance, we can see that buying a Prius would make you pay 55% more, and would save you 61.5% on gas. That sounds like good savings right ? The only caveat is that you pay for the car upfront, in cash, while you pay for gas over time. It does not matter that you get a loan for your car payment for this topic, since you are taking a loan with today's value and paying it over time. What this means is that %61.5 savings in the overall gas consumption may or may not make up for the premium you are having to pay for the car itself. Welcome to the magic of present value and compound interest.

The concept of present value comes into play here. In the simplest of terms, the gas you buy over time, although you pay the same amount of money every time, has less of a value today in monetary terms. So if you pay $100 every month for gas, the value of your yearly gas expenditure is not $1200 but less. (specifically, PV of $100 monthly payments with 3% market interest rate for a year is $1,180.73)  

One way to think about it is this: if you gave some amountyour money to invest in a CD, with no risk, you would get that money and some more at the end of the month. For any interest amount greater than zero, you would have to give less than $100 today to receive $100 at the end of the month.
If the monthly interest rate is 1% for instance, and if you had $99.00 today, it would be able to buy you $99.99 worth of gas for you at the end of the month. So in a way, $99 today is equal to $99.99 at the end of the month. From that, you can reach the conclusion that if you spend $100 a month, you could be given less than $1200 today and you would be able to cover your yearly gas expenditure. Present value calculates what that amount is.

What amount of money should you be given today, at present time, to be able to cover your monthly gas bill for a year ? That is the question present value answers.

The picture is more complex though, since how much you spend on gas depends on the gas price and the mileage you are putting on the vehicle. For the same driver, we can assume the same mileage and we can pick a reasonable gas price for this simulation, since it is the same gas price whether you are using a hybrid or conventional engine car. Let's assume that a driver drives an average of 1,000 miles a month and gas prices average about $3.80 a gallon. The monthly gas pricing for each vehicle is shown below.

Brand / Model Monthly Gas Bill
Toyota-Prius $ 76.77
Toyota-Corolla $ 124.59
Honda Civic Hybrid $ 86.36
Honda Civic $ 118.75

With the assumptions we are talking about (1000 miles per month and $3.80 per gallon of gas) we can now calculate what the savings are for 3, 5 and 7 year periods for a hybrid car owner. The comparison here takes Corolla and Prius, and Honda Civic and Honda Civic Hybrid. 
Gas Savings 3 year savings 5 year savings 7 year savings

These are great savings figures. In three years, with today's value, you would be saving quite a bit of money by driving a hybrid vehicle. But wait a minute, this does not take into account the money you would have paid upfront for the hybrid. If you bought a Toyota Prius vs. a Toyota Corolla, you would have paid about $14,287.50 more upfront. If you bought the Honda Civic Hybrid vs. the conventional engine Civic, you would pay $3,770 more. Let's put these values into the calculation and take a look at things once more.

Total Savings 3 years 5 years 7 years
Toyota  $ (12,643.05)  $ (11,626.07)  $ (11,139.97)
Honda  $ (2,656.35)  $ (1,967.62)  $ (1,638.43)

Wow !!! Look at these numbers. With the driving habits and prices we have outlined so far, if you owned a Toyota Prius for 3 years vs. owning a Toyota Corolla, you would have paid $12,643.05 more. The picture gets better with Honda Civic vs. Civic Hybrid, but you still pay about $2,656.35 more in three years. What does this mean ?

It means that buying a hybrid does not save you money. It is that simple. The whole sales pitch about people who are saving money so if you care about your wallet you should consider a hybrid is... misleading. The situation becomes more palatable if you pay less for the hybrid, but if you can negotiate that way for the hybrid, why could you not negotiate for a conventional car. There is the government tax credit $3500 to $4,000, which would certainly help. That credit is no longer available however, so if you are buying one today, a hybrid car is costly to own. The big issue here is that you are paying this difference upfront. This is money leaving your pocket as soon as you take the keys. If you are taking a loan to pay for the car, you are probably paying for this difference with a loan that is more expensive than 3% a year, which makes things even worse.

You could drive less, but interestingly driving less does not help. Driving more does. The hybrid cost advantage is unlocked as you use the car more. The more you drive, the more of the upfront payment you get back in payments, and by polluting more you save more. It is like the old TV commercials that talk about sales of things that you would never buy anyway and say that you are saving money. Not really. I am simply trying get my original investment back.

So I am convinced that there is absolutely no financial benefit to buying a hybrid. Well, at least to me there isn't. As of April 2012, Toyota has sold 2.87 million Prius units. At an average of $10,000 a piece price difference, Toyota has made about $28.7 Billion from Prius, vs. selling the same amount of cars in other comparable models (in this case, for simplicity we are taking Corolla). That is a large chunk of money. To give you an idea, Bill and Melinda Gates foundation has investments around $26 Billion. So Toyota has made more money that it can invest on the environment with Prius. And it did donate $1 Million in 2005. I am sure Toyota and other companies who build hybrids are donating in large amounts, but is it comparable to $28.7 billion extra that consumers are paying ? This number is a subset of the overall hybrid sales by Toyota, which is 4 million units.

We could argue that the investment is being made so that the hybrid manufacturers can improve their production. Well, that is called a stock market. You can buy a share of the company, the company then invests in things, and pays in dividends or stock value, or both. But in this case, none of that exists. Company makes money, you get the same thing that you would have gotten, more expensive, and feel good that you are good to the environment. Are you though ? Production of a hybrid is more expensive and hybrid cars don't live as long as conventional ones. The price difference is an indication of the additional cost of production, and that translates into environmental cost as well, since labor, energy and rare materials are spent during production. So it is not super clear how one helps the environment by buying a hybrid either. Not in a measurable way at least.

Here is my personal take on all of this data. In the end, hybrid ownership is like a donation check made out to cash. The money goes to car manufacturers, government (in form of sales tax on the car), and the car dealers as commission of the overall price. How much of it does the environment gets is not very clear. One thing is for sure, only rich people would be buying the hybrids right ? They are so expensive, there is clearly no financial return, you would have to care about the environment very much to donate over $10,000 in one sitting. I say that a hybrid owner must be really well off. It is better than driving a luxury car, since not only you are spending cash to feel good, but also you are doing it under the umbrella of giving to the greater good. Well, it turns out that people do buy hybrids and specifically Prius for status. That takes us to the podcast comment I made, Freakanomics covered this.

I wish you environmentally and economically savvy days ... May your decisions be easier than mine.