Multiples assignmets in a for loop clause.

1
2
3
4
5
 for hello, world in [ [:Hola, :Mundo],
                       [:Hallo, :Welt], 
                       [:Foo, :Bar]    ]
   puts "#{hello} #{world}"
 end

When to uses mock objects ?

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways

Wikipedia

Use mocks when you to :

  • improve test performances.
  • Remove dependencies of external systems.
  • control the behavior of a method.

Via MockFight

snippet : A benchmark in ruby (II)

require "benchmark"
ITERATION = 100_000

def measure(&block)
  ITERATION.times { block.call }
end

puts("PLATFORM: #{PLATFORM}")

br = Benchmark.bmbm do |x|
  x.report("{ }") do
    measure { }
  end

  x.report("string <<") do
    host_string = ""
    measure { host_string << "A" }
  end

  x.report("string +=") do
    host_string = ""
    measure { host_string += "A" }
  end

  x.report("2**16") do
    measure { 2**16 }
  end

  x.report("File write") do
    File.open("benchmark_out.txt", File::CREAT 
                                 | File::TRUNC 
                                 | File::WRONLY) do |f|
      measure { f.puts "A" }
    end
  end

  x.report("File read") do
    File.open("benchmark_out.txt", "r") do |f|
      measure { f.read }
    end
  end

end

File.open("#{PLATFORM}_benchmarks.txt", File::CREAT 
                                        | File::TRUNC
                                        | File::WRONLY) do |bf|
  bf.puts br
end

One not documented behavior im lambda

proc { |…| block } => a_proc, lambda { |…| block } => a_procEquivalent to Proc.new, except the resulting Proc objects check the number of parameters passed when called.
Ruby official doc

But at least are one more difference :

def foo
  f = Proc.new { return "return from foo from inside proc" }

  f.call # control leaves foo here

  return "return from foo"

end

def bar

  f = lambda { return "return from lambda" }

  f.call # control does not leave bar here

  return "return from bar"

end

puts foo # prints "return from foo from inside proc"

puts bar # prints "return from bar"

Wikipedia

Snippet : session expires in rails

  def check_auth
    if session[:admin_authenticated] 
      if session[:expires]  "login"
      end
    else
      redirect_to :action => "login"
    end
  end

The importance of reding Open Sources code.

Unless genius, most writers would have read hundreds of books before actually writing any. Most movie directors watch hundreds of movies before making any. Likewise, reading good code should be a precondition to write good software.

Rails and how he decide to render on errors

  1. Rails makes a distinction between local request and public requests.
  2. On error, two different things happen depending on if the request is local or public.
  3. With a local request, Rails internal templates are rendered optimized for developers and displaying exception details.
  4. With a public request, Rails renders either public/404.html or a static error message.

Via semergence

A good API must :

 Ruby have a very good set of features to desing API and thats why rails and other pseudo-DSLs make us feel really comfortable.  Closures/code blocks,  metaprogramming and method_missing method are the mos important.

I have been watching Joshua bloch track “how to design a good api and why matters” , its a really iteresant video. I must think about some points :

  • Easy to learn
  • Easy to use, even w/o doc
  • Hard to misuse
  • Easy to read and maintain code that uses it
  • Sufficiently powerfil to satisfy requirements
  • Easy to extend
  • Appropriate to audience – no such thing as a “perfect” API for everyone

When we design an API we must :

  • Start with a small (1 page) spec
  • TDD for API design
  • Minimize accessibilty – maximize information hiding
  • Class Design
    • Minimize mutability
    • If mutable, keep the state space small and well defined
  • Method design
    • Spending time on the API to make it easier is more important than performance
    • Provide programmatic access to all data available in String form
    • Overload with care – no two with same number of args
    • Use consistent parameter ordering
    • Don’t use exceptions for control flow, only for errors

snippet : A benchmark in ruby

An easy snippets thats show how to do a benchmark :

require 'benchmark'

require 'base64'Benchmark.bm(8) do |x|

  n   = 1_000_000

  hsh = { :id => 1, :name => 'Foo', :description => 'bar',

          :created_at => '2007-06-01 16:05:41.592507',

          :updated_at => '2007-06-01 16:05:41.592507', }

  str = Base64::encode64(Marshal.dump(hsh))

  x.report('delete!:') { n.times { str.dup.delete!("n") << "n" } }

  x.report('gsub!  :') { n.times { str.dup.gsub!(/n(?=.)/, '') } }

  x.report('linear :') { n.times { str = str.dup; str.gsub!(/n(?=.)/, '') } }

  x.report('scan   :') { n.times { str.dup.scan(%r|.{1,60}|).join } }

end

via pastie.

Two snippets on how to refactor a ruby application using block helpers.

Poor coding approach :
1, Insert HTML code as strings

<%= link_to "<strong>#{product.name}</strong><span>
            #{pluralize(product.topic_count(company), 'topic')}</span>",
    href, :class => "product_label" %>

2. Use condinional sentences to display content :

 <% if @user.rol == :admin %>
   Section only for admins
 <%end >

Solutions,

1. Replace the old lin_to with a block helper (via educate, liberate):

<% link_to browse_url(product), :class => "product_label" do %>  <%= product.name %>

(<%= pluralize(product.topic_count(company), 'topic') %>)

<% end %>

2. Use a code block helper to insolate the rol administation logic :

 <% @user.admin? do %>
   section only for admins
  <%end%>