Thu10Jun

  1. FAO Ruby/Rails developers

    How long do your CI builds take?

    How long is too long?

  2. Fri28May

  3. Use a different Ruby for each project with RVM and a .rvmrc file
  4. Mon05Apr

  5. Divide & Conquer?

    After reading that on embedded systems that when one wishes to divide a number by another, it is more perfomant to multiply by the divisor’s reciprocal instead. If I recall correctly this something to do with some embedded platforms lacking hardware to perform division and so it is emulated in some way, i.e. a lot slower.

    I was wondering what the performance difference between dividing by an integer or multiplying by its reciprocal in Ruby is.

    Benchmark code:

    require 'benchmark'
    
    Benchmark.bmbm do |x|
      x.report("divide:")   { 9999999.times { 999999999 / 8 } }
      x.report("multiply:") { 9999999.times { 999999999 * 0.125 } }
    end
    

    Ruby 1.8.7

    Rehearsal ---------------------------------------------
    divide:     2.160000   0.020000   2.180000 (  2.348516)
    multiply:   2.380000   0.010000   2.390000 (  2.542357)
    ------------------------------------ total: 4.570000sec
    
                    user     system      total        real
    divide:     2.230000   0.010000   2.240000 (  2.406294)
    multiply:   2.420000   0.020000   2.440000 (  2.594445)
    

    Ruby 1.9.1

    Rehearsal ---------------------------------------------
    divide:     1.110000   0.000000   1.110000 (  1.137086)
    multiply:   2.890000   0.020000   2.910000 (  2.953284)
    ------------------------------------ total: 4.020000sec
    
                    user     system      total        real
    divide:     1.110000   0.010000   1.120000 (  1.125234)
    multiply:   2.860000   0.010000   2.870000 (  2.891654)
    

    Ruby 1.9.2 preview release

    Rehearsal ---------------------------------------------
    divide:     1.160000   0.000000   1.160000 (  1.243541)
    multiply:   2.530000   0.020000   2.550000 (  2.723876)
    ------------------------------------ total: 3.710000sec
    
                    user     system      total        real
    divide:     1.160000   0.000000   1.160000 (  1.196763)
    multiply:   2.490000   0.020000   2.510000 (  2.591883)
    

    I tested on a new MacBook Pro 2.53 GHz 4GB. As you can see in 1.8.7 the difference is very small, but on the 1.9.x branch with a different VM, division has been significantly optimised while nominally speaking at least, multiplication performance appears to have slightly deteriorate. Don’t even think about multiplying/dividing a fixnum to/by a float or vice versa if your code may be deployed on JRuby.

    JRuby 1.4

    Rehearsal ---------------------------------------------
    divide:     1.960000   0.000000   1.960000 (  1.783000)
    multiply:  21.506000   0.000000  21.506000 ( 21.505000)
    ----------------------------------- total: 23.466000sec
    
                    user     system      total        real
    divide:     1.962000   0.000000   1.962000 (  2.079000)
    multiply:  23.535000   0.000000  23.535000 ( 23.535000)
    
    

    It turns out JRuby is an absolute dog when using floats and fixnums together in divide/multiply operations. Forget about it too if you’re looking at MacRuby…

    MacRuby 0.5

    Rehearsal ---------------------------------------------
    divide:     0.420000   0.010000   0.430000 (  0.444890)
    multiply:   0.420000   0.000000   0.420000 (  0.434119)
    ------------------------------------ total: 0.850000sec
    
                    user     system      total        real
    divide:     0.420000   0.000000   0.420000 (  0.427087)
    multiply:   0.420000   0.000000   0.420000 (  0.426598)
    

    Since MacRuby is a total BEAST across the board. Insane performance!

    s

    EDIT: These benchmarks were run in IRB. Using JRuby IRB enables ObjectSpace (FWIW Charles Nutter recently made a commit to trunk so that IRB doesn’t require ObjectSpace), which causes an incredible performance hit in JRuby. Running the benchmark as a script yields very impressive performance:

    Rehearsal ---------------------------------------------
    divide:     1.178000   0.000000   1.178000 (  1.097000)
    multiply:   1.078000   0.000000   1.078000 (  1.078000)
    ------------------------------------ total: 2.256000sec
    
                    user     system      total        real
    divide:     1.019000   0.000000   1.019000 (  1.019000)
    multiply:   1.022000   0.000000   1.022000 (  1.022000)
    
  6. Sun04Apr

  7. JRuby looks really exciting←link!
  8. Sun28Mar

  9. Proc.new vs lambda vs proc

    ruby-doc

    Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.
    def gen_times(factor)
      return Proc.new { |n| n*factor }
    end
    
    times3 = gen_times(3)
    times5 = gen_times(5)
    
    times3.call(12)               #=> 36
    times5.call(5)                #=> 25
    times3.call(times5.call(4))   #=> 60
    

    So what is “lambda” business about then? lambda is a method in the Kernel module, which is mixed in to every object, and so available EVERYWHERE in your code. lambda returns a object of class Proc, but it checks it’s arguments when it is called, i.e. it must be called with precisely the amount of arguments the block expects or an ArgumentError is raised.

    @proc   = Proc.new { |a,b,c| puts [a,b,c].inspect }
    @lambda = lambda   { |a,b,c| puts [a,b,c].inspect }
    
    @proc.call 1,2,3
    # => [1,2,3]
    @lambda.call 1,2,3
    # => [1,2,3]
    
    # Proc is chilled out. Proc just ignores any more arguments than it is expecting
    @proc.call 1,2,3,4,5,6,7,8
    # => [1,2,3]
    
    # Procs also pass in nil in lieu of missing arguments
    @proc.call 1,2
    # => [1, 2, nil]
    
    # lambda is not so chill
    @lambda.call 1,2,3,4,5,6,7,8
    # => ArgumentError: wrong number of arguments (8 for 3)
    @lambda.call 1,2
    # => ArgumentError: wrong number of arguments (2 for 3)
    
    

    Ok, what about this proc fellow then? The answer to that question is “That depends. Which version of Ruby do you use?”

    In Ruby 1.8.7 and earlier proc is synonymous with lambda. They do the same thing, i.e. return a proc object that checks its arguments when called. To me this represents the wrong behaviour.

    Maybe it’s just me, but I would expect proc to be a shortcut of Proc.new instead of a synonym for lambda. Something like this:

    module Kernel
      def proc(&block)
        Proc.new &block
      end
    end
    

    ln Ruby 1.9 that is exactly what it is, a convenient syntax for Proc.new. It is because of this I advise you never use it in your code, as it behaves very differently between these versions and you’re just asking for trouble as 1.9 adoption increases.

    Recapitulation:

    • Proc.new - Instantiates Proc that is agnostic re arguments
    • lambda - Instantiates Proc that checks arguments
    • proc - Inconsistent behaviour between 1.8 and 1.9 therefore avoid.

    S

  10. Ruby 1.9.x: j and jj

    j & jj the JSON conversant relatives of p & pp, i.e. they output JSON strings on one line or pretty print them over many lines with indentation respectively.

    ruby-1.9.1-p378 > require 'JSON'
     => true 
    ruby-1.9.1-p378 > obj = [{:foo => "bar", "baz" => [1,2,3,4,5]}]
     => [{:foo=>"bar", "baz"=>[1, 2, 3, 4, 5]}] 
    ruby-1.9.1-p378 > j obj
    [{"foo":"bar","baz":[1,2,3,4,5]}]
     => nil 
    ruby-1.9.1-p378 > jj obj
    [
      {
        "foo": "bar",
        "baz": [
          1,
          2,
          3,
          4,
          5
        ]
      }
    ]
     => nil
    

    Nice. Although it would be nicer if when you did this:

    ruby-1.9.1-p378 > j [{:first_10_natural_numbers => 0..9 }]

    You got this:

    [{"first_10_natural_numbers":[0,1,2,3,4,5,6,7,8,9]}]

    Instead of this:

    [{"first_10_natural_numbers":"0..9"}]

    Oh well.

  11. Sat27Mar

  12. class_eval vs instance_eval

    In Ruby you may have seen class_eval and instance_eval and thought to yourself “What is the difference?” They both accept a string or a block as an argument, but then they diverge:

    instance_eval evaluates a string as Ruby code or a block in the context of the object’s singleton class. Effectively it changes the value of self, the implicit receiver, to be that of the object’s metaclass, singleton class, eigenclass, or whatever else you may know it as.

    Methods on an object’s singleton class are defined on that object. If you call it on an instance of a class, the code evaluated by instance_eval will only apply to that instance. 

    instance_eval is not the only way to define singleton methods in Ruby. As usual in Ruby, there is a multitude of ways to skin a cat: 

    dude = "steve"
    
    # All these are equivalent
    
    class << dude
      def say_what_up
        "yo, my name is #{self}"
      end
    end
    
    def dude.say_what_up
      "yo, my name is #{self}"
    end
    
    dude.instance_eval do
      def say_what_up
        "yo, my name is #{self}"
      end
    end

    When you call it on an actual class, it has the effect of defining “class methods”. I put that in quotes because once you think of it in those terms it becomes clear that “class methods” do not actually exist, they are just singleton methods on another type of object, i.e. a class. Amazing!

    class Foo
      def self.foo
        "foo"
      end
    end
    
    class Foo
      class << self
        def foo
          "foo"
        end
      end
    end
    
    def Foo.foo
      "foo"
    end
    
    class << Foo
      def foo
        "foo"
      end
    end
    
    Foo.instance_eval do
      def foo
        "foo"
      end
    end
    

    These all do the same thing, i.e. define the “class method” Foo.foo that returns a string “foo”.

    So I did say earlier that code evaluated by instance_eval will only apply to that object. That’s not strictly true, although semantically it is. If you call on an actual class, it will be visible to classes that subclass it when Ruby can’t find it on that object. Ruby then goes off on its merry way up the inheritance chain looking for it in ancestor classes.

    Like so:

    Foo = Class.new
    
    Foo.instance_eval do
      def foo
        "foo"
      end
    end
    
    Bar = Class.new Foo
    
    puts Bar.foo
    
    #=> foo

    class_eval

    class_eval switches the value of self to its receiver. This can only be called on a module or class and not an instantiation of those objects. A method defined in a string or block supplied to instance_eval has the effect of defining instance methods for that class or module. (Although a module cannot be instantiated, it can be mixed into a class, making the class respond to those instance methods. More on this at a later date.)

    class Foo
      def to_s
        "foo"
      end
    end
    
    Foo.class_eval do
      def to_s
        "foo"
      end
    end

    class_eval is also aliased as module_eval. I tend to use module_eval if the object that I’m manipulating is a module as opposed to a class. I think it makes my code more readable and is a good style to adopt.

    You can’t use class_eval on an object instance. Try it, you’ll get a NoMethod error. This makes perfect sense!

    That’s all I can think of for now

    S

  13. Fri26Mar

  14. To Yield Or Not To Yield? That Is The Question…

    Today I was looking quite closely at Rails 3, specifically the changes to the routing API.

    # Rails 2.x
    ActionController::Routing::Routes.draw do |map|
      map.resources :posts
    end
    
    # Rails 3.x
    AppName::Application.routes do
      resources :posts
    end
    

    The first thing I noticed was the omission of a block variable. So I thought to myself “WTF? Is the block being instance_eval’ed instead of yielded to?”

    Yes, it turns out it is, well instance_exec‘ed to be precise. I always thought instance_eval’ing a block was an antipattern

    So why the change? Is this still representative of current thinking?

  15. DRY Much?

    I’ve been looking through the source of ActiveSupport and Rails in general, and I’ve noticed this particularly verbose style of monkeypatching a multitude of objects with the same behaviour:

    # Can you safely .dup this object?
    # False for nil, false, true, symbols, numbers, class and module objects; true otherwise.
     
    class NilClass #:nodoc:
      def duplicable?
        false
      end
    end
     
    class FalseClass #:nodoc:
      def duplicable?
        false
      end
    end
     
    class TrueClass #:nodoc:
      def duplicable?
        false
      end
    end
     
    class Symbol #:nodoc:
      def duplicable?
        false
      end
    end
     
    class Numeric #:nodoc:
      def duplicable?
        false
      end
    end
     
    class Class #:nodoc:
      def duplicable?
        false
      end
    end
     
    class Module #:nodoc:
      def duplicable?
        false
      end
    end
    

    It’s definitely not DRY, which is a key tenet of the Rails way. So why not do the same thing like this?

    [NilClass, FalseClass, TrueClass, Symbol, Numeric, Class, Module].each { |klass| klass.class_eval { def duplicable?() false end } }
    
    # Or even…
     
    [NilClass, FalseClass, TrueClass, Symbol, Numeric, Class, Module].each do |klass|
      klass.class_eval { def duplicable?() false end }
    end

    Don’t give me “It’s less readable” because it’s not my friend, (well it is if you’re reading on the Tumblr Dashboard, but look here for better formatting) especially to the sort of person who would be going into source code to look around. So what other reasons can you come up with? 

  16. Mon22Mar

  17. Maybe why you don’t see recursion used much in Ruby

    I’ve become interested in recursion and functional programming lately in the interests of sharpening one’s saw, and was interested to see how recursion performed in Ruby.

    Consider the following code:

    require 'benchmark'
    
    def recursive_factorial(n)
      n == 0 ? 1 : n * recursive_factorial(n-1)
    end
    
    def iterative_factorial(n)
      (1..n).reduce :*
    end
    
    Benchmark.bmbm do |x|
      x.report("recursive:") { 10000.times { recursive_factorial 1000 } }
      x.report("iterative:") { 10000.times { iterative_factorial 1000 } }
    end
    

    Yields the following benchmark:

    Rehearsal ----------------------------------------------
    recursive:  53.670000   2.560000  56.230000 ( 57.035829)
    iterative:  32.540000   2.330000  34.870000 ( 35.629017)
    ------------------------------------ total: 91.100000sec
    
                     user     system      total        real
    recursive:  77.420000   3.740000  81.160000 ( 88.844745)
    iterative:  41.870000   3.200000  45.070000 ( 64.231568)
    

    Considerable difference in performance. The iterative method looks a lot more simple and elegant too in my opinion.

    EDIT: jrwest - obviously, but is the difference always as stark?

  18. Fri19Mar

  19. Stud muffin devs need only apply.

    Stud muffin devs need only apply.

  20. Thu18Mar

  21. Ruby Quines

    A quine is a program that prints out it’s own source code. More on that here.

    s='s=;puts s[0,2]+39.chr+s+39.chr+s[2,36]';puts s[0,2]+39.chr+s+39.chr+s[2,36]

    This contains a string which consists of a reference to itself and everything before and after itself. It is assigned to the local variable s so the string can be reused to take substrings that match the code declared before and after the string. Capiche?

    s="s=%p;puts s%%s";puts s%s

    Huh?! Well this one is even more terse. It prints a string and uses itself to format itself using the String instance method %. Very meta! The meta-ness doesn’t end there either, as %p is like self.inspect when evaluated in the context of Kernel#sprintf. The two % together just mean a literal %. 

    Finally…

    puts File.read __FILE__

    or

    puts File.read $0

    A program that reads itself. That’s just cheating though, isn’t it? :)

  22. Wed17Mar

  23. ActiveRecord models are bloated.

    They handle object persistence, the object graph, business logic, and proxy data to other objects (accepts_nested_attributes_for). accepts_nested_attributes_for was the straw that broke the camel’s back for me.

    More on this later.

  24. Fri12Mar

  25. Quick Tip: Ruby Monkeypatch Fail

    I’m contracting at the moment, developing an internal CRM application. For authorisation I’m using Ryan Bates excellent CanCan. However, due to application requirements, I can’t control access at the resource level, it has to be done at the controller level. For this I created a little patch to extend ApplicationController:

    module SG
      module CanCan
        module ControllerAdditions
          def restrict_access(options ={})
            before_filter(options.slice :only, :except) { |c| c.unauthorized! unless c.can? c.params[:action].to_sym, c.class }
          end
        end
      end
    end
    
    ApplicationController.extend SG::CanCan::ControllerAdditions if ApplicationController
    

    This adds a class method to ApplicationController that checks if the user can access the given action on the controller. This works fine in development mode… for the first request, then I get a no method error! It works fine in test and production until the cows come home.

    I thought about this bizarre problem for a few minutes and realised that the problem was probably related to the environment configuration. 

    # In the development environment your application's code is reloaded on
    # every request.  This slows down response time but is perfect for development
    # since you don't have to restart the webserver when you make code changes.
    config.cache_classes = false
    

    Of course ApplicationController is being reloaded for each request in development mode! So when my initializer runs, ApplicationController is extended. However, from the second request on, the class is reloaded i.e. no extensions.

    The solution? Extend ActionController::Base instead. Since it’s not an application class/module it isn’t reloaded for each request.

    module SG
      module CanCan
        module ControllerAdditions
          def restrict_access(options ={})
            before_filter(options.slice :only, :except) { |c| c.unauthorized! unless c.can? c.params[:action].to_sym, c.class }
          end
        end
      end
    end
    
    ActionController::Base.extend SG::CanCan::ControllerAdditions if ApplicationController
    

    This will work in all environments without a hitch.

  26. Fri05Mar

  27. Object#tap - Ruby’s K Combinator

    Say we want a method that returns an instance of the class Logger. We want this method to either return a previously instantiated object, if it exists, or we want to instantiate one. In Ruby we have a nice piece of syntactic sugar known as “or equals”, previously covered here. To briefly recapitulate what it does is return the object on the lefthand side when it is not nil, or it evaluates the righthand side, assigns it to the lefthand side, and return that value.

    def logger
      @logger ||= Logger.new(STDOUT)
    end

    Very nice, beautiful, and simple. However what happens when you need to call a method on the resulting object? Something that can’t be passed as an argument into the constructor? Using the same example of our logger method, one might want different datetime formatting on their log entries.

    def logger
      @logger ||= Logger.new(STDOUT)
      @logger.datetime_format = '%c'
      @logger
    end

    Terrible. The datetime setter is being called each time the logger method itself is called. Horrible, wasteful, unnecessary, and ugly. We could get around this by putting a return statement in there, but this too is ugly and quite quickly the method becomes bloated. I believe it is better to embrace what Ruby is: a synthesis of the most powerful and flexible computer science concepts and ideas.

    New in Ruby 1.9 and backported to 1.8.7 is Object#tap, Ruby’s implementation of the K combinator. Tap makes some really beautiful code possible. Simply put, what it does is take the object it is called on, pass it into a block, whatever is inside the block is evaluated, and the object is returned even if the block returns something different. This also means you can get your method chaining game on nice!

    Let’s see what our logger method would look like using this functional style:

    def logger
      @logger ||= Logger.new(STDOUT).tap { |o| o.datetime_format = '%c' }
    end

    Come on dude! How beautiful is that? One line of ninjitsu, and I believe perfectly clear once you know what Object#tap is.

    Conceptually, Object#tap is very simple. When called on an object, the objects yields to a block, passing itself in as a block variable and finally returns self after that. So, if you’re still on 1.8.6 and are going a little green with envy right now, don’t worry, thanks to Ruby’s open classes you can still get the good stuff.

    Object.class_eval { def tap() yield self; self end }

    Ok, enough one liners for one day. :p

    S