The Ten-Day MBA

The Ten-Day MBA cover

Chad Fowler, in his book “The Passionate Programmer” recommended a book The Ten-Day MBA. The reason, why he recommend it, is the fact that successful programmer should know the basics of marketing. E.g. to be aware how much his work is worth.

The Ten-Day MBA is an overview of fundamental basics of economy, business, finance, leadership and even real estate. In my opinion, this book is not only for programmers. It is for everyone! You can find there difference between monetarists and Keynesian economy, the product life cycle (from factory to customer), the difference between corporation and private business, time estimation of projects, business strategies etc.

I strongly recommend this book. I was studying at University of Economics 3 years (Bachelor degree). This book contains all most important concepts I learned there.

You can find it on amazon.


Ninja Rails Developer

Warning: this configuration was tested only on MacOS X.

To create default project in Rails we just need to run command:

rails new my_app

However it creates project without many useful gems. I found nice Gem-set and some configuration hacks in Michael Hartl’s tutorial.

Instead of standard test framework (TestUnit) he use RSpec (which is more popular among Rails developers). To generate project without standard test, run command:

rails new my_app --skip-test-unit

Then use his Gemfile (this link is kept up to date). Copy it a paste into my_app/Gemfile. I recommend to uncomment everything (to use all Gems from the file).

Once Gemfile is modified, you need to install gems:

bundle install

Then you can run RSpec test:

bundle exec rspec

You may need to point the tests’ directory:

bundle exec rspec rspec/

It would be nice to run them with just ‘rspec’ command. To do that we need to run following commands (if we used RVM to install Rails):

rvm get head && rvm reload

cd ~/projects/my_app

bundle install --without production --binstubs=./bundler_stubs

After those steps you should be able to run RSpec with:

rspec

You should get a warning, that to maintain this possibility you need to add following line to ~/.bash_profile if it exists, otherwise add it to ~/.bash_login:

source ~/.profile

Michael Hartl’s Gem file contains ‘guard’. It allows us to run RSpec test each time, when we change some file (after save).

To initialize guard (if all above steps are performed, otherwise you need to add ‘bundle exec ‘ at the beginning):

guard init

It creates Guardfile in main project directory, which specify when tests should be run (which files should be monitored). To run guard:

guard

The last improvement is use the test server Spork. It allows to run tests faster. Without Spork, RSpec needs to reload entire Rails environment before run the tests (in each run). Spork loads the environment once, and then maintains a pool of processes for running future tests. Unfortunately it works only on POSIX systems (which means: doesn’t work on Windows).

To setup spork run:

spork --bootstrap

Then change spec/spec_helper.rb file to something like that:

require 'rubygems'
require 'spork'

Spork.prefork do
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  require 'rspec/autorun'

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
  RSpec.configure do |config|
    config.mock_with :rspec
    config.fixture_path = "#{::Rails.root}/spec/fixtures"
    config.use_transactional_fixtures = true
    config.infer_base_class_for_anonymous_controllers = false
  end
end

Spork.each_run do
  # This code will be run each time you run your specs.
end

You also need to configure RSpec to automatically use Spork. To do that, modify .rspec file:

--color
--drb

To run Spork:

spork

You can test difference between running tests with and without spork.

time rspec

In my case it was 4.821s without Spork, and 0.784 with Spork.

The disadvantage of Spork is that after e.g. changes in database we need to restart it.

The screencast showing advanced setup by Michael Hartl is available for free here. If you use SublimeText (as I do), you can follow this screencast to adjust it for Rails development. After that you will be able even to run tests from SublimeText!


Sign in with facebook (OAuth): how to and threats

Many websites provide possibility to authorize with OAuth protocol (e.g. using facebook account).

How to

In ASP.NET application it is very easy to implement. Check this 3 minutes long screencast by Scott Hanselman.

In Rails it is a little bit more complex, but also not big deal. There is nice Rails cast #360 about it (12 minutes).

Threats

However it is good to know what data we are providing when we click ‘Login with facebook’. I implemented facebook auth with omniauth-facebook library (according to above rails cast). I was surprised when I look at the source code.

This is auth data available for developer, when we sign in with facebook:

{
  :provider => 'facebook',
  :uid => '1234567',
  :info => {
    :nickname => 'jbloggs',
    :email => 'joe@bloggs.com',
    :name => 'Joe Bloggs',
    :first_name => 'Joe',
    :last_name => 'Bloggs',
    :image => 'http://graph.facebook.com/1234567/picture?type=square',
    :urls => { :Facebook => 'http://www.facebook.com/jbloggs' },
    :location => 'Palo Alto, California',
    :verified => true
  },
  :credentials => {
    :token => 'ABCDEF...', # OAuth 2.0 access_token, which you may wish to store
    :expires_at => 1321747205, # when the access token expires (it always will)
    :expires => true # this will always be true
  },
  :extra => {
    :raw_info => {
      :id => '1234567',
      :name => 'Joe Bloggs',
      :first_name => 'Joe',
      :last_name => 'Bloggs',
      :link => 'http://www.facebook.com/jbloggs',
      :username => 'jbloggs',
      :location => { :id => '123456789', :name => 'Palo Alto, California' },
      :gender => 'male',
      :email => 'joe@bloggs.com',
      :timezone => -8,
      :locale => 'en_US',
      :verified => true,
      :updated_time => '2011-11-11T06:21:03+0000'
    }
  }
}

We provide our email(!), timezone and even location! Actually I was not aware of that. I thought facebook provides just basic info like name and photo.

We should think twice before we sign in to some website with OAuth. Especially due to providing our email address. Malicious websites can use it for sending spam.


Sending email from Rails application

It took me a while to configure sending email from Rails application. I went through many different tutorials, blogs, StackOverflow posts etc. Step, by step I found working configuration.

To send emails I use ActionMailer. First you need to generate mailer:

rails generate mailer UserMailer

It will create UserMailer class in app/mailers directory. In this class we need to define our method for sending emails:

class UserMailer < ActionMailer::Base
  default from: "from@example.com"

  def send_email(user_email, content)
  	@user_email = user_email
  	@content = content
  	mail(to: "your@mail.com", subject: "Email from mysite.com")
  end
end

Then in the directory app/views/user_mailer we need to create template for our email: send_email.html.erb (this name must match the name of action created in UserMailer class):

<!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <p>
      From: <%= @user_email %>
    </p>
    <p>
      <%= @content %>
    </p>
  </body>
</html>

(*) If you do not want to send html you can create plain text and name file send_email.text.erb.

Now, the hardest part. Configuration of smtp. You need to add it to config/environments/development.rb (or test.rb or production.rb). I found this configuration working for gmail:

# set delivery method to :smtp, :sendmail or :test
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true

  # these options are only needed if you choose smtp delivery
  config.action_mailer.smtp_settings = {
    :address        => 'smtp.gmail.com',
    :port           => 587,
    :domain         => 'gmail.com',
    :authentication => :login,
    :user_name      => 'your_gmail@gmail.com',
    :password       => 'your_password',
    :enable_starttls_auto => true
  }

The last thing is call ActionMailer from our app:

UserMailer.send_email(params[:from], params[:content]).deliver

Form for sending email can looks like that:

<%= form_tag '/send_email', method: 'post' do %>
	<div class="field">
		Email<br />
    <%= email_field_tag :from %>
  </div>

	<div class="field">
		Content<br />
    <%= text_area_tag :content, nil, rows: 10, cols: 25 %>
  </div>

  <div class="actions">
    <%= submit_tag "Send", class: "btn btn-large btn-primary" %>
  </div>
<% end %>

For that you need to configure action in controller and match route e.g.:

match '/send_email', to: 'your_controller#your_action'

Method send_mail (from UserMailer class) can have as much parameters as you need. It can be also 0. In above example, the params are just rendered in the email template (send_email.html.erb file).


Getting started with Ruby on Rails

Ruby on Rails logo

Recently I decided to learn Ruby on Rails. When you start learning a new technology you are always looking for the best available materials (to learn as efficient as possible). I did the same (using Google and StackOverflow). Fortunately I found The Best Way to Learn Ruby on Rails and I followed the recommended steps. With small modifications (extensions).

First of all I extended first step. Instead of just going through “Try Ruby” exercises I also read first chapter of Seven Languages in Seven Weeks (which is about Ruby). It was very good move, because this book is written in the way to show the flavors of language by comparison with others. I am a .NET guy, who was coding in PHP, C++, Java and Python before. Because of that I was more interested in the differences between Ruby and these languages, than in programming from ground up. I also reviewed (not read) Humble Little Ruby Book. It is a little bit more deep, but it gives you solid Ruby basics.

I was working with Rails on Windows and on Mac. Installing on Windows is very easy when you use RubyInstaller. There is also version for Mac. However on Mac you can also install Rails using RVM. In that case I recommend you installation screncast by Michael Hartl. On Windows I used RubyInstaller, but on Mac I took advantage of Michael Hartl’s screencast. Additionally you may also need SQLite Database Browser to browse your database easily. I did not know about it at the beginning and I was using rails dbconsole. Browsing with SQLite Database Browser is much more comfortable!

When I had Rails installed I went through Jeffrey’s Introduction to Rails. During that I tried to follow him, by writing code on my machine, but many times he was too fast. I needed to pausing video very often and even scrolling back to see written command (he was changing screens to quickly). Anyway it was very nice introduction and I recommend it. But you can skip rewriting and trying code he is writing. Just watch it to get a flavor of Rails.

After that I went through Rails for Zombies tutorials. I was very lucky, because Code School had promotion in May 18-19, and they provided Rails for Zombies 2 for free in these days. These tutorials are very solid. The exercises force you to learn by typing, because you cannot proceed to next level, until you do not finish all tasks.

Agile Web Development with Rails cover

With all basics gained as described above I started a book: Agile Web Development with Rails. I really like this book. It has 3 parts:

  • Getting started (Rails installation, create first app, quick Rails architecture overview)
  • Building application (tutorial)
  • Rails in Depth

The longest part of the book is the tutorial(2nd). Through this part you are creating an complete application exploring different Rails features. Unfortunately this book is a little bit outdated. Authors use ruby version 1.8.7 and Rails 3.0.0. I installed most recent versions: ruby 1.9.3p392 and Rails 3.2.13. Sometimes you need to fix the code (e.g. Chapter 11 – Task F: Add a Dash of Ajax). During that I found Ruby on Rails documentation very useful.

The last part is going deep into Rails. I really recommend this part! It is not only about Rails, but also about Web Applications and MVC architecture in general: how browser works, how requests are handled by Rails app, session, cookies etc.

When I was in the middle of book I was a little bit angry (because it is outdated) and I switched to Ruby on Rails tutorial by Michael Hartl, which is strongly recommended on StackOverflow. Well…guys at SO are right. This is really good piece of knowledge not only about Rails, but also about using git, css, Bootstrap and Web Development in general. I really enjoyed it! If you do not want to buy videos, you can just read the free book (it is the same content as in videos and more). There are also nice videos describing advanced setup for Rails development on Mac and SublimeText configuration for Rails. Actually this tutorial covers Rails development from A to Z.

As a summary to the book and Michael Hartl’s tutorial I reviewed Rails Guides. It is a nice overview for most important rails features. Can be also used as a reference. Some of the RailsCasts are also useful.

I wanted to try a few different tutorials/books to see different approaches. E.g. Michael Hartl use rspec for unit tests, but the authors of Agile Web Development with Rails are using rails testing framework.

My adventure with Ruby (on Rails) lasts almost two months. Now I can admit that ROR is a very powerful and developer friendly framework. It contains many features, which are already grabbed by ASP.NET (e.g. migrations, bundling). What was surprising for me, you do not need IDE to develop Rails apps. I use SublimeText2 (awesome editor!) and it is really enough. Some Rails developers use VIM or Emacs. Of course there are some IDEs such as RubyMine or Aptana Studio. I tried both. RubyMine seems to be pretty cool…but I stick with SublimeText. Additionally, during Rails development you spend lot of time with console (to create/run/undo migrations, create models/controllers, run tests etc.).

If you want to start Rails development, my recommended steps are:

You might also find these tools/resources useful:

What I like in Ruby on Rails? The syntax, convention over configuration and lots of implemented features in the framework layer. Moreover: Rails are just cool.