Sun15Aug

  1. The Symbol#to_proc myth←link!

    Symbol#to_proc performing like a dog is simply just not true anymore.

  2. Sat07Aug

  3. Stabby Lambdas & Curried Functions

    Starting a new project at work in Ruby 1.9, I noticed there is a new syntax for creating lambdas:

    a = ->(a,b) { a**b }

    This is equivalent to the conventional

    b = lambda { |a,b| a**b }

    Thus:

    a[2,5] == b[2,5]

    My opinion is split on the aesthetic appeal of this new syntax, sure it’s brief but it’s also erlang-y. Fortunately it does have a useful feature, i.e. the ability to give default values to block parameter. This is not possible:

    lambda { |a,b=2| a**b }

    This is:

    ->(a,b=2) { a**b }

    Currying, i.e. partial application of functions also appear

    pow = ->(a,b) { a**b }.curry
    => #<Proc:0x00000100b021b8 (lambda)>
    square = pow[2]
    => #<Proc:0x00000100aff2b0 (lambda)>
    square[2]
    => 4
    square[4]
    => 16
    square[16]
    => 256
    

    Proc#call has also been aliased as Proc#=== meaning one can use lambdas in case statements… WUUUUUTTT!

    S

  4. Sat24Jul

  5. Quick Tip: Ruby Class Definition

    Everyone knows this syntax

    class Foo
    
    end

    This is cleaner when you just need to quickly define an empty class:

    Foo = Class.new

    I’m writing this ActiveRecord compliant in memory model implementation called Glamazon for this secret project I’m on at work. I used Class.new’s ability to take a block as the class body to include my library into a testable class, e.g.

    Mule = Class.new { include Glamazon::Base }

    In other Ruby code you might frequently see this used to define error classes:

    class SpecialError < StandardError
    end

    This is way cleaner:

    SpecialError = Class.new StandardError

    s

  6. Thu22Jul

  7. A Tasty RSpec Morsel

    RSpec’s let method is not hugely known but it’s very useful for DRYing up one’s specs. It accepts a symbol and a lazily evaluated block that defines a method when the method name is called

    let(:foo) { puts 'METAPROGRAMMING FTW!' }

    Even less known is that due to way Ruby (< 1.9)  works under the covers, one can pass in block variables and have the method magically accept arguments when it’s called.

    I used this at work to stub out different API responses, and I came up with this little piece of sugar

    let(:api_stub) { |code,response| FakeWeb.register_uri :get, %r|#{API_ENDPOINT}|, :status => [code, response] }
    
    # Usage:
    api_stub '401', 'Unauthorized'
    

    Yum!

  8. Sat17Jul

  9. Processing streaming JSON asynchronously is a piece of cake with YAJL and EventMachine

    At work we are planning a redesign of our architecture into a services oriented style. It makes a lot of sense for us and will enable us to scale the areas of the application that need it while avoiding us wasting extra resources on areas of the application that are doing just fine as they are. It’s some seriously sexy shit, trust me. That and working with insanely smart cats has me jumping out of bed every morning.

    One of the first things I needed to do was find away to consume a stream of data asynchronously. Since the data is a stream is delivered in arbitrary chunk sizes, not as discrete JSON objects I had a problem. Somehow I had to parse this.

    Turns out it isn’t a problem. Thanks to YAJL and EventMachine

    Check the Beautiful, simple, sweet, sweet code 

    P.S. If you run the code, observe the general asininity of Twitter’s user base… Fuck Twitter.

    Love

    S

  10. Sun11Jul

  11. Shoulda: with vs. without

    ActiveRecord spec without shoulda:

    describe Address do
      let(:address) { Factory.build :valid_address }
      %w(street_address locality region postal_code country).each do |attribute|
        it "is invalid without #{attribute}" do
          address.send "#{attribute}=", nil
          address.should_not be_valid
          address.errors.on(:"#{attribute}").should include "can't be blank"
          address.send "#{attribute}=", 'valid input'
         address.should be_valid
        end
      end
    end
    

    ActiveRecord spec with Shoulda:

    describe Address do
      it { should validate_presence_of :street_address }
      it { should validate_presence_of :locality }
      it { should validate_presence_of :region }
      it { should validate_presence_of :postal_code }
      it { should validate_presence_of :country_name }
    end
    

    Even using a healthy dash of metaprogramming to make the first example as brief as possible, it’s clear shoulda wins hands down for brevity, readability, and concision.

    s

  12. Thu10Jun

  13. FAO Ruby/Rails developers

    How long do your CI builds take?

    How long is too long?

  14. Fri28May

  15. Use a different Ruby for each project with RVM and a .rvmrc file
  16. Mon05Apr

  17. 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)
    
  18. Sun04Apr

  19. JRuby looks really exciting←link!
  20. Sun28Mar

  21. 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

  22. 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.

  23. Sat27Mar

  24. 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

  25. Fri26Mar

  26. 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?

  27. 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?