Blog

Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Saturday, July 20, 2013

mysql2 installation issues on OSX 10.8.4 (homebrew install)

Installing mysql2 Ruby gem on 10.8.4 with a home-brew install may raise the following error:

mysql.h is missing. please check your installation of mysql and try again.

Removing the following options from cflags in mysql_config vim `which mysql_config` resolved the issue:

-Wno-null-conversion -Wno-unused-private-field

Credit: https://github.com/brianmario/mysql2/issues/383

Friday, March 9, 2012

Testing Terminology: Spies, Stubs and Mocks

When referring to the definitions of Spies, Stubs and Mocks I like to return to XUnit Test Patterns:

  • Test Spy: "We use a Test Double to capture the indirect output calls made to another component by the SUT for later verification by the test."
  • Test Stub: "We replace a real object with a test-specific object that feeds the desired indirect inputs into the SUT."
  • Mock Object: "We replace an object the SUT depends on with a test-specific object that verifies it is being used correctly by the SUT."

You may have noticed that a Spy and Mock seem to have similar definitions, and do serve similar purposes, however Mocks specify expectations up-front and don't require assertions in contrast to Spies, that verify after the fact. Here's an example that compares Rspec Mocks with Bourne's Spies:

SUT is an abbreviation for System Under Test.


The above patterns are collectively know as Test Doubles: "We replace a component on which the SUT depends with a test-specific equivalent." Rspec's built-in mocking library includes a double method/alias, see An Example using RSpec double, mock, and stub.

Double-Ruby (RR) is another example of a test double framework implemented in Ruby.

Saturday, July 30, 2011

Upgrade RVM and Ruby 1.9.2p290

I've been a little lazy and haven't updated my RVM installation (version 1.1.3, now 1.6.31) for a while and have been stuck on Ruby 1.9.2p0. This morning I upgraded, here's what I did:

$ rvm get head
$ rvm reload
$ rvm install 1.9.2-p290
$ rvm upgrade 1.9.2-p0 1.9.2-p290

Hmm… Got some errors, here's the output:

Are you sure you wish to upgrade from ruby-1.9.2-p0 to     ruby-1.9.2-p290? (Y/n): y
Migrating gems from ruby-1.9.2-p0 to ruby-1.9.2-p290
Are you sure you wish to MOVE gems from ruby-1.9.2-p0 to ruby-1.9.2-p290?
This will overwrite existing gems in ruby-1.9.2-p290 and remove them from ruby-1.9.2-p0 (Y/n): y
Moving gemsets...
Moving ruby-1.9.2-p0 to ruby-1.9.2-p290
Making gemset ruby-1.9.2-p290 pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@brandizzle to ruby-1.9.2-p290@brandizzle
Making gemset ruby-1.9.2-p290@brandizzle pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@default to ruby-1.9.2-p290@default
Making gemset ruby-1.9.2-p290@default pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@global to ruby-1.9.2-p290@global
Making gemset ruby-1.9.2-p290@global pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@peters-guide to ruby-1.9.2-p290@peters-guide
Making gemset ruby-1.9.2-p290@peters-guide pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@refinery to ruby-1.9.2-p290@refinery
Making gemset ruby-1.9.2-p290@refinery pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@shoedazzle to ruby-1.9.2-p290@shoedazzle
Making gemset ruby-1.9.2-p290@shoedazzle pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@spree to ruby-1.9.2-p290@spree
Making gemset ruby-1.9.2-p290@spree pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@sproutcore to ruby-1.9.2-p290@sproutcore
Making gemset ruby-1.9.2-p290@sproutcore pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Moving ruby-1.9.2-p0@storeworks to ruby-1.9.2-p290@storeworks
Making gemset ruby-1.9.2-p290@storeworks pristine.
ERROR: Error running 'rvm gemset pristine' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//gemset.pristine.log
Do you wish to move over aliases? (Y/n): y
Updating alias default to point to ruby-1.9.2-p290@default
Do you wish to move over wrappers? (Y/n): Y
Do you also wish to completely remove ruby-1.9.2-p0 (inc. archive)? (Y/n): Y
ERROR: Error running 'rvm remove ruby-1.9.2-p0 --archive --gems' under ,
please read /Volumes/Data/Users/nicholas/.rvm/log//rvm.remove.log
Successfully migrated ruby-1.9.2-p0 to ruby-1.9.2-p290
Upgrade complete!

Note that I opted to move over aliases, wrappers and completely remove my old ruby-1.9.2-p0.

Looking at the gemset.pristine.log I had the following errors for each gemset:

[2011-07-30 09:08:04] rvm gemset pristine # under ruby-1.9.2-p290@brandizzle
/Volumes/Data/Users/nicholas/.rvm/scripts/functions/environment: line 235: rvm: command not found

So for each gemset I executed the following:

rvm gemset pristine 

This seemed to work fine. Next, I checked out the errors in rvm.remove.log:

[2011-07-30 09:08:32] rvm remove ruby-1.9.2-p0 --archive --gems # under ruby-1.9.2-p0
/Volumes/Data/Users/nicholas/.rvm/scripts/functions/environment: line 235: rvm: command not found

Looks like the remove of my old 1.9.2 install failed, so I ran it manually:

rvm remove ruby-1.9.2-p0 --archive --gems 

Boom! Everything is updated and working.

Saturday, April 16, 2011

Installing RubyGems with no Rdoc/RI

Finally took the step today of not generating RDoc and Ri when installing Ruby Gems by default by adding the following to ~/.gemrc.

install: --no-rdoc --no-ri
update: --no-rdoc --no-ri

Saturday, April 9, 2011

Code examples from Associative Arrays with James Edward Gray II

I watched David Brady's pod call with James Edward Gray II discussing Associative Arrays. There are definitely some gems (no pun intended) in this video. While watching the video I transcribed the code examples below.

Associative Arrays with James Edward Gray II from David Brady on Vimeo.

Friday, January 14, 2011

Never use rescue blindly

On a recent project I was horrified to see various inline rescues. Here are three examples:

# Example 1
def friend_recommended_picture
  friend.recommended_picture rescue ""
end

# Example 2
params[:search][:skip_conversion] = true rescue nil

# Example 3
item_image = Product.find_by_id(product_id).images.find(:first, :conditions => 'attachment_file_name like "%example.jpg"').attachment.url(:mini) rescue ''

In all of these examples I the author is protecting themselves from a NoMethodError with a NilClass.

My preference is to always use the try method (provided in Rails 2.x and standard in Ruby 1.9):

# Example 1
def friend_recommended_picture
  friend.try(:recommended_picture) # returns nil if friend is nil
end

In Rails, this can be cleaned up using the delegate class method:

delegate :recommended_picture, :to => :friend, :allow_nil => true, :prefix => true

For the second example I would prefer this, although there is a little more code involved (clarity over cleverness):

# Example 2
params[:search][:skip_conversion] = true if params[:search]

And for the final example, well this is a bit of a mess. Let's clean up the call:

item_image = item_image(Product.find(product_id))

And encapsulate the various scopings within the correct classes.

# products_helper.b
def item_image(product)
 product.example_image.try(:attachment) {|attachment| attachment.url(:mini) }
end

# models/post.rb
def example_image
  images.examples.first
end

# models/images.rb
named_scope :examples, :conditions => 'attachment_file_name like "%example.jpg"'

This last example illustrates well that the careless use of rescue nil is a symptom of other issues such as poor encapsulation.

There are plenty of examples of using rescue such as on Ruby Inside:

h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"        # => "No name"

This still makes me feel dirty inside. Yes it is working on a Hash, but what if h becomes a more complex object, then that rescue could be obscuring other exceptions. My preference would be:

h[:name].try(:downcase) || "No name"

Jay Fields also has an interesting use for inline rescue. One of the commenters mentions "its important to use them judiciously." I suspect the inline rescue is a victim of cargo culting and 99% of the time there is a better solution.

Thursday, January 13, 2011

Interfacing with Web Services? Checkout Tammer Saleh's "Coding for Failure"

Last year when interfacing with several Web services for a project I found Tammer Saleh's "Coding for Failure" indispensable. Although it was presented two years ago, it's far from out of date.

You can check it out on the Confreaks website and download the slides from here (the link on Tammer's website is broken).

Specifically I found Tammer's summary of different exceptions helpful which I have included here:


See slides for handling in controllers and rake tasks and notification using HopToad.

Thursday, October 28, 2010

CarrierWave, an alternative to PaperClip for Uploading Files in Rails or Ruby Applications

I recently switched to CarrierWave: "Classier solution for file uploads in Ruby for Rack, Rails, Merb and Sinatra". Why? Here's three reasons:

  1. Uploading logic/handling is extracted into a separate class. Hence the tag "Classier solution". It addresses my sensibility for Single Responsibility and separation of concerns.
  2. It maintains a cache across redisplays. Meaning the user does not need to upload a file again, if other fields are invalid on the model.
  3. Dead easy upload from a remote URL.

Definitley give it a try. Anything I have missed? Let me know in the comments.

Tuesday, September 21, 2010

Translating Booleans in I18n files

I got caught out on this today when creating a translation file that included translations for boolean values:

# config/locale/en.yml
  false: No
  true: Yes

t(false) did not translate, i.e. en, false. Ok so to be on the safe side, let's not use Ruby keyword for a key.

# config/locale/en.yml
  false_value: No
  true_value: Yes

t("#{false}_value) translated to false. OK, getting a little close, but not quite what I want.

# config/locale/en.yml
  false_value: "No"
  true_value: "Yes"

t("#{false}_value) translated to Yes. Perfect!

Thursday, September 9, 2010

How to display Facebook Profile information when using FBGraph Ruby Gem for an Authorized User

When using the FBGraph Gem for Facebook I wanted to display profile information for the logged in user authorized with Oauth2. It wasn't immediately clear to me from the documentation on how to do that.

Once you have a authorized user and a client instance, call:


You can then access various attributes:


Also note there is a fgraph gem as well, don't get them mixed up!

RSpec #stub vs. #stub!

Confused by #stub vs. #stub!? Consider #stub! deprecated and use #stub. #stub is simply an alias for #stub!. #stub! was defined in the API at a time when RSpec's authors weren't clear on the intention of "bang" methods in Ruby. Quoting David Chelimsky's email on RubyForge:

The original method was stub!, which I will confess to introducing, and for the wrong reasons, due to my misunderstanding of the meaning of ! in ruby methods. I recently added stub (with no !) with no particular fanfare, as I don't intend to remove stub! (at least not any time soon). Right now the docs don't make it clear, so I need to fix that - but I'd say that stub() is the method to use and stub!() is there for backwards compatibility.

The confusion is compound in The RSpec Book (B15.0 printing, July 29, 2010) where there is as single reference to #stub! on page 199.

References:

Wednesday, September 8, 2010

Ruby Hook Methods

Here is a list of all the hook methods in Ruby. This list is taken from the screencast Some Hook Methods in the The Ruby Object Model and Metaprogramming series.

Method-related Hooks

  • method_missing
  • method_added
  • singleton_method_added
  • method_removed
  • singleton_method_removed
  • method_undefined
  • singleton_method_undefined

Class & Module Hooks

  • inherited
  • append_features
  • included
  • extend_object
  • extended
  • initialize_copy
  • const_missing

Marshalling Hooks

  • marshal_dump
  • marshal_load

Coercion Hooks

  • coerce
  • induced_from
  • to_xxx

Saturday, September 4, 2010

Ruby RDoc Example

This is an example RDoc file I sometimes refer to which illustrates documenting classes and methods. Yes I now I should probably move to YARD.

Saturday, August 21, 2010

Defining Methods in Ruby using #instance_eval

Last week I discussed the differences between class_eval and instance_eval.

I stated there were two basic rules to follow when choosing which method to use:

  1. When the object is a class use class_eval, you will typically be using the def keyword
  2. When the object is an instance use instance_eval

When we use instance_eval to define methods where are the located? The are stored in the instance’s singleton class. I will write more about Ruby’s singleton class in the future, but for now you may want to read Ola Bini’s excellent post on the subject.

Let’s look at an example:

class MyClass; end

my_instance = MyClass.new

my_instance.instance_eval do
  # add the method to the instance's singleton class
  def foo
    "bar" 
  end
end

puts my_instance.foo # => "bar" 

another_instance = MyClass.new

begin
  # since the method exists only on the my_instance singleton class, calling
  # it on another_instance will raise a NoMethodError exception

  puts another_instance.greeting
rescue NoMethodError
  puts "The foo method does not exist" 
end

What happens when we call instance_eval on Class?
MyClass.instance_eval do
  def baz
    "qux" 
  end
end

puts MyClass.baz # => "qux" 

As you can see it defines a class method. I would argue that you should never use instance_eval on a class (although my last post regarding the subject suggested you could). I feel for a beginner in Ruby it may confuse. Stick to class_eval for class objects, and instance_eval for instances. If you need to dynamically define a class method then use this technique:

MyClass.class_eval do

  class << self

    # define .quux as a class method
    #    
    def quux
      "corge" 
    end
  end

  def grault
    "garply" 
  end
end

puts MyClass.quux # => "corge" 
puts my_instance.grault # => "garply" 

Saturday, August 14, 2010

When to use Ruby's class_eval vs. instance_eval

When to use class_eval vs instance_eval? Here are some basic rules to follow:

  1. When the object is a class use class_eval, you will typically be using the def keyword
  2. When the object is an instance use instance_eval

There is an important subtle difference between the two.

  • class_eval changes self and the current class
  • instance_eval only changes self

If you don't need to use def then what should use use? Well you could use MyClass.instance_eval. But as Paolo Perrotta states from Metaprogramming Ruby:

"…pick the method that best communicates our intentions."
class Book
  
  # define a class instance variable
  #
  @books_published = 0

  # define the attr_accessor as a class method
  #
  class << self
    attr_accessor :books_published
  end
    
  def initialize(title)
    @title = title
    Book.books_published =+ 1
  end
end

b = Book.new("Metaprogramming Ruby")

Book.class_eval do
  def introduction
    "Thank you for reading #{@title}"
  end
  
  private
  
  def units_sold
    100_000
  end
end

b.instance_eval do
  puts @title # access an instance variable => Metaprogramming Ruby
  puts units_sold # send a message to a private method => 100000
end

puts b.introduction # => Thank you for reading Metaprogramming Ruby

# I don't care if this is a class or an instance
Book.instance_eval do
  puts @books_published # => 1
end

Friday, August 6, 2010

Questions asked in a Ruby on Rails Job Interview

Here are some real life Ruby and Rails questions that you maybe asked in a job interview. These are based on my experience in applying for contract positions. I have not provided the answers, I will leave that as an exercise to the reader (as they say).

General Object-Oriented and Programming Questions

  1. What is polymorphism?
  2. What is overriding and oveloading?
  3. What does a test suite contain? (e.g. setup, fixtures, assertions)

Ruby Theory Questions

  1. What is a Singleton Method?
  2. What is the difference between a block, lamda and proc?
  3. What is the super class of Class?
  4. What is the super class of Module?
  5. What is a class variable vs. a constant?
  6. What do you like about Ruby?

Ruby Practical Questions

  1. Print the numbers 1 to 10 in the console
  2. Create a custom method to iterate over an array contain negative and positive numbers and only print the positive numbers

General Algorithm Questions

  1. Reverse an interger, e.g. 12345 => 54321, without converting to a string
  2. Perform a Binary Search on an array of numbers to find a target number

Rails Questions

  1. What is the difference between #destroy and #delete?
  2. What modules make up Rails? (e.g. ActiveRecord)
  3. What is ActiveSupport?
  4. What two extension methods does ActiveSupport contains?
  5. What association methods does ActiveRecord provide?
  6. Which table is the foreign key related in a belongs_to association?
  7. What annoys you about Rails?
  8. Describe a situation where you had to work outside of the Rails stack or customize Rails  to make it meet project requirements?

Database Questions

  1. What is an index?
  2. How is an index implemented?
  3. When would you use an index?
  4. What are the first things to look at with a slow query containing a join?
  5. What is an outer right join?

These questions are ones that I have been asked personally. Please add questions you have been asked in the comments. I'm sure there are some I am missing so I will update this post as they come to mind.

 

Wednesday, July 7, 2010

Ruby's Object#try method

Yesterday I blogged about implicitly testing for nil, relying on Ruby's definition of truth, rather than the explicit Object#nil? to keep code terse.

Here's another example of keeping code terse when handling nil values with Object#try. This is particularly helpful when working with ERB:

# in ERB template
@order.user.name if order.user
The simplified version:
# in ERB template
@order.user.try(:name)

Something I didn't know previously to writing this post, is Object#trysupports arguments similar to Object#send.

Object#try was added to ActiveSupport in Rails 2.3.2.

Monday, July 5, 2010

Keeping your code terse, testing for "nil"

On a recent project, I was seeing many occurrences of this statement:

if !order.user.nil?
  # do something ...
end

While this is correct, it's not idiomatic Ruby. Ruby is a terse language. Let's keep our code terse as well. Consider how Ruby defines truth:

"Ruby has a simple definition of truth. Any value that is not nil or the constant false is true." (Agile Development with Rails, 3rd Edition, pg 319).

This means testing for "nil" is redundant. We can therefore shorten our code to:

if order.user
  # do something ...
end

Nice and clean.

Please note this blog is no longer maintained. Please visit CivilCode Inc - Custom Software Development.