Wednesday, January 11, 2012

My GIT workflow (w rebase)

This is usually a popular topic: the following is what work for us at https://microhealth.org

..start the new branch from master
git checkout master
git pull
git checkout -b my_new_feature
..work and commit some stuff
git checkout master
git pull
git checkout my_new_feature
git pull
git rebase master
git pull
git commit -m 'rebased from master' 
..work and commit some stuff
git checkout master
git pull
git checkout my_new_feature
git pull
git rebase master
git commit -m 'rebased from master' 
..finish the feature
git checkout my_new_feature
git pull
git checkout master
git pull
git merge my_new_feature

git push origin master 
 
..Just delete your branch because after a rebase in upstream, your branch is no longer used
git branch -D my_new_feature
 
(to delete permanently from the server: git push origin :my_new_feature) 
 
Don’t rebase branches you have shared with another developer:
If you have pushed your work in the new branch, use merge instead.
 
 
Note: I will update the post in the next days.

Saturday, January 7, 2012

Using STI on Rails. Tips

If you ever think of using Single Table Inheritance on Rails, forget about it. It will cause more headaches than benefits. It is simply that Rails ActiveRecord does not work as you can expect with all the possible combinations / associations you can set on your objects: there are bugs, 'features' and tricks that made me lose a lot of time these last days. However, if you still think it fits into your models, keep reading.

When To use STI ?

As introduction, I highly recommend reading this excellent compilation of tips about STI : http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html .
Well, lets make is as painless as possible:

Quick recipe

Lets suppose that you have a User model, that will derive in Man, Child and Woman subclasses. As all share the same data (columns) but the behaviour is different it makes sense using STI in here.

1 - Make all users share the same controller
The first thing I want is that all users share the same controller: show, index, destroy, ... all the actions do the same for all Users.
However, paths automatically generated for a @child, @man, @woman, @user, are different by default: new_child_path, new_man_path, .... That is a pain in view helpers as form_for and  fields_for
This is solved overwriting the 'model_name' class method of the base class: make all the models in the inheritance chain share the same name

(in user.rb)
class << self
    def inherited(child)
      child.instance_eval do
        def model_name
          User.model_name
        end
      end
      super 

    end
end

now, all subclasses use the users resource paths in the view helpers
2 - Remove all those ugly 'where type = ' conditions in your SQL queries

By default, when you do a Man.find(id) it includes a 'type = 'Man'' condition in your queries. For example:

Man.find(3) -> "SELECT from users WHERE id = 3 and type = 'Man';"
This is true for finds, updates and destroys. Far from being useful, it can make your records are not found under certain conditions (i.e changing the type of the record after its creation). That errors can go unnoticed since they dont raise errors, but have no effect.
For example, if we try to promote a child to a man:

@child.type = 'Man' 
#now, Rails side considers it as of 'Man' type, but DB still has it as 'Child'
@child.save!

it translates to
UPDATE users SET type = 'Man' WHERE id = 3 AND type = 'Man';
As DB still has the record stored as a Child, it is not found, and so never gets updated. A subtle error, that can lead to future problems (remember that it wont raise any failure)

My solution makes these 'where type' conditions removed by default:


(in user.rb)

class << self
    def finder_needs_type_condition?
      #http://apidock.com/rails/ActiveRecord/Base/finder_needs_type_condition%3F/class
      false
    end
end

Note that as (an undesired) side effect,  SQL operations over derived classes  lose the 'type' conditions by default.

More specifically

User.count == Child.count == Man.count
are translated to the same query:
SELECT COUNT(*) from users;

Woman.all == User.all
are translated to the same query:
SELECT * from users;

You must include it explicitly
User.where(:type => 'Woman').all

you can alleviate the problem adding a scope on all the derived classe

(in user.rb)
class << self
    def inherited(child)
    #after the code on the step 1


      def of_same_type
        where({:type => self.name}) # type == class.name
      end

    end 
end

Now you can do

Child.of_same_type.all

3 -Make you can easily promote one user to other type

There is a litlle gem in ActiveRecord called 'becomes' method
It allows you to 'cast' your object to other type:

@grown = @child.becomes(Man) #now @grown is the @child, cast to a Man.

The new object will behave as a Man, while have the original data form the child (name, age, etc). Keep in mind that 'becomes' returns a newly instantiated object, that shares the variables with the original object, so you are only handling a 'Man' when manipulates this new object (@grown). The original child is not really casted (code) to a man.

To make the change permanent you still have to save the object (@grown.save). However under some circumstances you are not sure if save is invoked on the new instance (@grown) or in the original (@child): for example using autosave associations, or if it it re bound in a belongs. In that cases you want it to be saved with the new type (Man) whether the save is in the original or in the casted instance. You only have to 'patch' the instance method from ActiveRecord::Base

(in user.rb)

    def becomes(klass)
      if self.class == klass
        return self
      else
        #backported patch from https://github.com/rails/rails/commit/e781853
        became = super(klass)
        became.type = klass.name unless klass.descends_from_active_record?
        became
      end
    end

4 - Consider polymorphic relationships

Whenever you are using a polymorphic relationship on a model with STI inheritance, there is a surprising thing (or not so surprising) that will happens where this relation is persisted.


Lets suppose that we have a has_pictures plugin that sets a polymorphic relationship. You can attach a picture to  User, Flat and Car models

(in picture.rb) 
belongs_to :picture, :polymorphic => true, :inverse_of => :item

You can have pictures for Users, Cars and Flats
has_one :item, :dependent => :destroy, :as => :posteable, :inverse_of => :picture

As in polymorphic relationships in Rails, Picture has two columns: item_type and type_id that are used to find the 'item' the picture owns: in type column you stores the class name of the item.

However Rails does a weird thing here: it stores the 'base' class in the type column of the item that is saved. That means that a Child, is stored with item_type set to 'User' .
It made me lose a day of work to realise that Rails works this way: it was not my fault.

If that does not suits you, there are plugins to store the very class of the item.
for Rails 3.0 , for 3.1 .


For other reasons I ended using an extra column to store the derived type (via :before_save) and kept the item_type storing the base class. But these plugins work well.


5 - Packing everything together
I finally wrote a module to reuse everything listed before.
Whenever I want to use Inheritance in AR models I just extend HasStiInheritance .

For example. Lets say that we have an User class, with AmericanUser, EuropeanUser and AfricanUser subclasses (every other user defaults to base User). These classes exist only to provide different implementation of some methods (i.e. the format addresses and phone numbers differently).

I declared User class as

class User < ActiveRecord::Base
  # include / extends
  extend HasStiInheritance
  ...
end

class  AmericanUser < User
   ...
end

class  EuropeanUser < User
   ...
end

class  AfricanUser < User
   ...
end

and I have only to remember using 'of_same_type' if I want to retrieve users of a given continent.

EuropeanUser.of_same_type.all #will list all europeans. OK

European.all #WRONG. retrieving ALL users, since we removed 'where type=XXX' clauses

I paste the module I am using now:

module HasStiInheritance
  #about structure, @see http://yehudakatz.com/2009/11/12/better-ruby-idioms/

  #constants here

  #class methods here

  def has_sti_inheritance
    include InstanceMethods
  end

  def define_class_method name, &blk
    #from http://blog.jayfields.com/2007/10/ruby-defining-class-methods.html
    (class << self; self; end).instance_eval { define_method name, &blk }
  end

  def finder_needs_type_condition?
    #do not include where type == klass_name in all the finders, even for subclases. That will helps 'AR.becomes' usage
    #http://apidock.com/rails/ActiveRecord/Base/finder_needs_type_condition%3F/class
    false
  end

  def of_same_type
    where(nil) # the base class does not need filtering by type
  end

  #As all users share the same controller / routes, we must patch the route generation for that resources:
  # Ex: => we want users_path , not european_users_path, american_users_path etc
  #http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html
  def inherited(child)
    #here, self is the base class
    base_model_name = self.model_name
    child_model_name = child.name

    child.define_class_method :model_name do
      base_model_name
    end

    child.define_class_method :of_same_type do
      where({:type => child_model_name}) # type == class.name
    end
    super
  end
  #class methods above

  #instance methods here

  module InstanceMethods

    def becomes(klass)
      if self.class == klass
        return self
      else
        #backported patch from https://github.com/rails/rails/commit/e781853  for 'becomes' method
        became = super(klass)
        became.type = klass.name unless klass.descends_from_active_record?
        became
      end
    end

  end
  #instance methods above
end




FIN

Friday, December 16, 2011

Avoiding Rails's 'validates_uniqueness_of' hits the Database

Disclaimer: I am now working with Rails 3.0.X, so this can be solved in newer branches (or not).

Sometimes something that starts as an stupid doubt takes you to useful improvements.

This morning, I was wondering if ActiveRecord is smart enough to avoid hitting the Database with an Update, when you save an unchanged object. My intuition said that none UPDATE should be done if nothing really has changed. So, doing a 'save' is always safe.

I fired up the console and activated the SQL log (as described here ). It turned out that ActiveRecord is smart enought to avoid issuing an SQL UPDATE if object is unchanged.

However I noticed a SELECT access while saving. Mmmm ....... from nowehere?

Well, it was certainly from somewhere:

 validates_uniqueness_of :username

This innocent line was fired on each validation, even if username didnt changed. The solition was really simple:

validates_uniqueness_of :username, :if => :username_changed?

The check is skipped when no really needed.
Profit!





Thursday, October 13, 2011

Concat in place for Javascript arrays

This one is like black magic.
Javascript Array's concat method creates a new array with the concatenation of 2 arrays. However doing so in place is what you need most of the time:

being:
var a = [1,2,3] , b = [4,5,6];

Push does not work, since it works with  individual elements
a.push(b);
>>> [1, 2, 3, [4, 5, 6]] 
a try with 'concat' wont work:
a.concat(b)
>>> [1, 2, 3, 4, 5, 6] //returns a new array, where (a is still [1,2,3] )

but the trick is doing:
a.push.apply(a,b);
>>> [1, 2, 3, 4, 5, 6] // where a is [1, 2, 3, 4, 5, 6]




(*)To understand how apply works: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply http://trephine.org/t/index.php?title=JavaScript_call_and_apply



Tuesday, September 27, 2011

Rails: The power of 'inverse_of'

There is a 'less known' feature of ActiveRecord associations that is very handy: the ability of marking an association as the mirror of another :inverse_of

The best is to rescue an example from the oficial documentation

class Dungeon < ActiveRecord::Base
  has_many :traps, :inverse_of => :dungeon
  has_one :evil_wizard, :inverse_of => :dungeon
end

class Trap < ActiveRecord::Base
  belongs_to :dungeon, :inverse_of => :traps
end

class EvilWizard < ActiveRecord::Base
  belongs_to :dungeon, :inverse_of => :evil_wizard
end
 
dungeon = Dungeon.first
wizard = dungeon.evil_wizard 



In a normal configuration, doing wizard.dungeon will hit the database and instantiate a new 'dungeon' (2 instances of the same object). 
 
With :inverse_of , Active record is aware of the relation and will use the same instance in memory. This has 2 benefits:
- we save a DB call
- as both 'dungeons' are the same instance, modifications on dungeon are seen from wizard (an the otehr way around)
 
Without :inverse_of , a modification on dungeon, is not seen by wizard.dungeon what can lead to subtle errors.
 
+1 for :inverse_of 
 
 

Saturday, September 10, 2011

Capistrano, Database.yml and how to deploy without exposing your database passwords

The other day we wanted to secure our database, changing the user (instead of root) and password that Rails uses. Having them harcoded in database.yml makes it unsafe.

Fortunately we deploy through Capistrano, and there is a recipe for deploying using database credentials previously stored in the target machine. This way, database.yml is not available from source code and credentials remain private.

Everything is available as a gist here ( http://www.simonecarletti.com/blog/2009/06/capistrano-and-database-yml/ ) but I want to complete the information to save you some time.

The recipe is split into 2 tasks:
- generating the database.yml in the target machine (that will end with a cap deploy:setup )
- deploying , but using the database.yml in the target machine (that will end with the usual cap deploy)

Steps:
  1. Download the gist AND save it in /config/capistrano_database_yml.rb
  2. Follow Requirements point in the gist doc (or in the link above)
  3. Follow Usage point in the gist doc (or in the link above)
    1. Note that you must add a require line in your capistrano deploy.rb . This line should be: require "config/capistrano_database_yml" . Since it is searched in your $LOAD path
  4. Create a custom template as in the Custom template section of the gist doc.
    1. In our case we ask for user and password
    2. Save the template in config/deploy/database.yml.erb
    3. There is an error in the doc, at least for Rails 3. To make deploy prompt for user or password, use the usual arb syntax: <%= %> 
    4. We end with something like for the .erb:
      base: &base
        adapter: mysql2
        encoding: utf8
        pool: 5
        host: localhost
        timeout: 5000
        username: <%=Capistrano::CLI.ui.ask("Enter MySQL database username: ")%>
        password: <%=Capistrano::CLI.ui.ask("Enter MySQL database password: ")%>
      development:
        database: my_app_development
        <<: *base
      test:
        database: my_app_test
        <<: *base
      staging:
        database: my_app_staging
        <<: *base
      preproduction:
        database: my_app_preproduction
        <<: *base
      production:
        database: my_app_production
        <<: *base
  5. When the erb is saved. you can run the cap deploy:setup (or cap deploy:setup if you are in a multistage)
    1. this will create a database.yml in your_target_machine /shared/config/database.yml
    2. during this task you were asked for the username and password, and they will be written in the database.yml
    3. revise that the generated database.yml have the right privileges: will be accessible only to  the user you deploy and run teh application with
  6. Once done. You can deploy the application in the usual way. It will use the new database.yml
    1. cap deploy(or cap deploy)
For Jenkins, you must create (or copy) the database.yml to each of the jenkins 'projects'. As it runs test, you only need a database.yml with 'test' section. Revise the access rights of this file also (ex: chmod for Jenkins user only).
The location of databse.yml per project will be(in our case is):
/var/lib/jenkins/jobs//workspace/config/database.yml
 
Profit! 


P.S. As a bonus, take a look to this compilation of capistrano recipes:

https://github.com/webficient/capistrano-recipes


Rails: Log SQL queries to console

This is a quick tip.
Whenever you need to study sql accesses of your code, you can do it during a console session. Just need to configure the logger:

rails c
logger = Logger.new(STDOUT);ActiveRecord::Base.logger = logger;ActiveResource::Base.logger = logger;

 It will log every sql query to the console.