How to get better error messages for an associated model.
Hey there. Let's assume you have some set like this
class User < ActiveRecord::Base
  has_one :profile , :dependent => :destroy
end


class Profile < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :first_name, :last_name
end

And you create the profile in the same view as your user. How do you validate those first_name and last_name fields with a friendly message for your user?
Well, you could use validates_associated, but you would end up with a message like "Profile is invalid". Now, how friendly is that?

To obtain a more precise message, use this on you user.rb

def validate
  if self.profile
    self.profile.errors.each do |error|
      self.errors.add_to_base error.join(' ')
    end
  end
end
Difference between is_a? and instance_of?

Hi Sirs.

There is a difference between a bunch of methods that appear that they to the same job, but they won't.

The methods instance_of?, is_a? and kind_of? do related jobs, but not the same job.

For example is_a? and kind_of? do the same job, they return true if the caller is an instance of the method argument, if the caller is an instance of every superclass in his inheritance tree or if the argument method is a module included in the caller.

The instance_of? is more specific, it returns true just if the caller is an instance of the method argument.

Let me show some examples:

module Hand
end

class Animal
end

class Mamal < Animal
  include Hand
end

class Dog < Mamal
end

dog = Dog.new

puts dog.instance_of?(Dog)    # true
puts dog.instance_of?(Mamal)  # false
puts dog.instance_of?(Animal) # false
puts dog.instance_of?(Hand)   # false

puts dog.is_a?(Dog)    # true
puts dog.is_a?(Mamal)  # true
puts dog.is_a?(Animal) # true
puts dog.is_a?(Hand)   # true 

Remember that is_a? and kind_of? do the same job.

See you.

Diff entre respond_to? e respond_to

Um pequeno tutorial em português pra diferenciar melhor respond_to? e respond_to. Não parece ter muita não? Mas o tio Chuck Norris vai me ajudar a esclarecer melhor isso aqui.

respond_to? é um método do Ruby Core como você pode ver, e não do Ruby On Rails, ele basicamente verifica se determinado objeto responde a um método, como o nome sugere mesmo.

Por exemplo:

class Chuck < Object
  def norris
    puts "the man"
  end
end
chuck_norris = Chuck.new
p chuck_norris.respond_to?("norris") # true
p chuck_norris.respond_to?("mr_t") # false

Já o respond_to, sem o ponto de interrogação (eles fazem parte do nome do método) faz parte do ActionController do Ruby On Rails. Ele coloca suporte a Web Service na sua aplicação, isso quer dizer que ele consegue resolver o tipo do recurso que você deseja.

respond_to do |format|
  format.html # render por default nome_da_acao.html.erb
  format.js # render o nome_da_acao.rjs
  format.xml { render :xml => @chuck.to_xml } # coloca o chuck pra xml e envia
end

Com esse código na action você poderia usar, por exemplo:

http://localhost:3000/nome_da_acao.html
http://localhost:3000/nome_da_acao.xml

Ou realizar uma chamada JS unobstrusive usando AJAX.

Isso ai, espero ter ajudado.

Export the database models to YML fixtures

Hi Sirs,

Many tutorials over the web shows how to load data from fixtures. But, if you want to migrate your mysql data to a postgresql database?

We can export our data to fixtures, and after that we can load the fixtures to every database management system we wish.

Let's go to the rake task:

desc "export the database models to YML fixtures" 
task(:models_to_fixtures => :environment) do 
  ActiveRecord::Base.establish_connection(
    :adapter => 'postgresql', # mysql, sqlite3
    :encoding => 'utf8',
    :database => 'cnxs_development',
    :username => 'username',
    :password => 'secret'
  )
  ActiveRecord::Base.connection

  if ENV['MODELS'].nil? || ENV['MODELS'].blank?
    raise "Please enter valid models names separated by coma. Ex: MODELS=User,Account"
  end

  models = ENV['MODELS'].split(',').collect { |arg| arg.camelize.constantize }

  models.each do |model|
    output = {}
    collection = model.find(:all)
    collection.each do |object|
      output.store(object.to_param, object.attributes)
    end
    file_path = "#{RAILS_ROOT}/tmp/#{model.table_name}.yml" # /tmp/
    File.open(file_path, "w+") { |file| file.write(output.to_yaml) }
  end
end

Here you need to fill your database attributes like you do in the /config/database.yml.

You will call the command line:

$ rake models_to_fixtures MODELS=<your model names separated by coma>

For example:

$ rake models_to_fixtures MODELS=User,Post

All your model data will be stored on /tmp/ directory.

Download this rake task here.

See you.

Clean Objects with find method

Hi Sirs.

An important trick on the famous ActiveRecord::Base find method.

When you are in development time of your application, and you do some query on your database query editor, is a good practice to use the limit clauses and selects just the columns you want.

In the find method we can do it with the :limit and :select arguments.

For example in our code when we try to authenticate some user we got it like:

find(:first, :conditions => [query, hash], :select => "id, email, login")

The returned object contains just the id, email and login attributes. Clean object.

Password and other attributes do not appears in the returned object =]

Simple development practice, but very important too.

See you.

Some Thoughts on Some Thoughts on Security
I've been reading a great paper by Daniel J. Bernstein, the creator of a qmail, and wow, what a pearl of wisdom. One of the most clarifying and straight to the point works on code security I have ever read. He (quite correctly) makes a parallel between the code security and the amount on exploitable bugs (EB), stating that it is the major problem on the code, regarding security. And then gives some answers to that problem, along with a couple of common distractions of the programmer while coding that helps those EB creep on our code base (CB). Let's review then, starting with the distractions, and I'll try to make some links with my favorite unambiguous tool of choice, Ruby.
  1. Chasing attackers. The point here is give some thought to respond to tomorrow's attacks, and not being trapped by the anti-virus mentality of being only responsive to aggressors. Perhaps the dynamic nature of Ruby would help with that, but I think it is more a personal posture problem than anything else.
  2. Minimizing privilege. Here, what is being said is that the old principle of least privilege is fundamentally wrong. How so? Well, it might (!) reduce the damage done by security holes, but never fixes these. Plus, IMO, it might even give users a false sense of security. Again, it is more of a way of a personal way of thinking (but what isn't? :P ).
  3. Speed, speed, speed. Here I think rubists have some advantage. Since we work on a language that is 'slow', usually we tend to not place emphasis on premature optimization. I think this quote summarizes the thinking here:
    Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil. —Knuth in [13, page 268]
Now, to the answers. These are also 3, and they are codependent connected to each other:
  1. Eliminating bugs. I think everyone saw that one coming. But even so, Daniel's down to earth advices on it are a very worthwhile reading. I think I can summarize him on this section by saying (and that is a plus to rubists too), simplify stuff. Simplify interfaces, UI, parsing. Elegance is not a luxury, it is a way to obtain security. Following that logic we come to.
  2. Eliminating code. Heck, here I'll quote his quote, and be done with it.
    To this very day, idiot software managers measure 'programmer productivity' in terms of 'lines of code produced,' whereas the notion of 'lines of code spent' is much more appropriate. —Dijkstra in [9, page EWD962–4]
    But as our systems grow, and our time and budgets remain the same or are diminished, and as programmers get more dumb, something has to give right? Wrong (don't know about the last part though).
  3. Eliminating trusted code. That is somewhat more difficult I think, but it says that a program should do what it is meant to do, nothing more, and trust as few sources of data as possible. KISS and all that stuff.
I would love to hear any input on that. Until next time people.