Underscore and classify
May 6, 2008
These are two Rails helpers that could be very useful when injecting new instance methods in a class.
underscore
Converts from a class name to a underscore attribute.
>> 'MyClassName'.underscore => my_class_name
classify
Inverse method from underscore.
>> "cool_articles".classify => "CoolArticles" >> "comment".classify => "Comment"
Both, combined with singularize and pluralize, allows us to handle parent/child methods in a very handy way. For example:
elements_in_ = self.send(parent).send(self.class.to_s.pluralize.underscore)
or things like
Kernel.const_get(table_model.to_s.classify).find(:all) #Kernel.const_get gets an string and retrieves the class.
Procs ‘n’ blocks
May 1, 2008
A block in Ruby is an expression delimited by braces that has, to try to put it simple, no life by itself. Thus if we write:
irb(main):001:0> {|x| x*x} SyntaxError: compile error
we’ll get a compile error. But blocks can be very powerful and go by the hand with other important concept in Ruby, namely the Procs. Procs, put again in a simple way, are blocks given life, thus are blocks bounded to some variables they can work with. To create a new proc, we can simply call the constructor of the class Proc or the kernel reserved word lambda, what will get us to the same thing, except that the latter will provide us argument checking. Thus:
irb(main):002:0> my_proc = Proc.new{|x| x*x} => #<Proc:0x00006a7c@(irb):2> irb(main):003:0> my_other_proc = lambda{|x| x*x} => #<Proc:0x00086640@(irb):3> irb(main):005:0> my_proc.call(5) => 25 irb(main):006:0> my_other_proc.call(5, 4) (irb):3: warning: multiple values for a block parameter (2 for 1) from (irb):7 TypeError: can't convert Array into Integer from (irb):3:in `*' from (irb):3 from (irb):7 from :0 irb(main):007:0> my_other_proc.call(5) => 25
Notice that a proc is executed by using the reserved word call. That means that we have to use it instead of yield when we are passing a proc rather than a block to a method:
irb(main):032:0> def gimme_those_five irb(main):033:1> 5.times {yield} irb(main):034:1> end => nil irb(main):035:0> gimme_those_five{puts "hi"} hi hi hi hi hi => 5
but
irb(main):038:0> def gimme_just_one(kind) irb(main):039:1> kind.call irb(main):040:1> end => nil irb(main):041:0> gimme_just_one lambda{puts "hi"} hi => nil
A handy enumerable to integer mapper creator
March 13, 2008
class EnumerableAttribute attr_reader :values def initialize(*args) @values = Hash.new 0.upto(args.size-1) do |i| @values[args[i].to_s] = i end @values.each do |key, value| EnumerableAttribute.class_eval do define_method key do value end end end end end
This class allows the dynamical creation of enumerable types mapped to integers in the database, starting from 0. The constructor will take a list of symbols representing the keys and will create a Hash that will map each key to one integer value. Once created, we can have access to the Hash via the method values or to the integer value of each key via the method called like the symbol.
E.g.
class Car include EnumerableAttribute end >> engine_type = Car::EnumerableAttribute.new(:diesel, :gasoline, :solar) => #<EnumerableAttribute::EnumerableAttribute:0x2467f5c @values={"diesel"=>0, "gasoline"=>1, "solar" =>2}> >> engine_type.values => {"diesel"=>0, "gasoline"=>1, "solar" =>2} >> engine_type.gasoline => "1
Enjoy! 🙂
Ruby on rails certifications
December 6, 2007
There are none so far.
Neither for only the Ruby language.
Official certifications, I mean. The Java unofficial certification community JavaBlackBelt has a beta exam for Ruby certification. Yes, it’s still a beta because the number of questions on their database so far is not enough to release the exam. So if you are a Ruby programmer and you are willing to collaborate, you can start taking a look at the exam objectives and writing some questions for them.
Understanding Ruby symbols
December 4, 2007
Symbols are one of the most misunderstood Ruby features. Let’s try to explain it as lay as possible.
The way I finally catched it is thinking about symbols as constants, whose value is the same as their name. The same as the integer 5 has the name 5 and the value 5, the symbol :thing has the name thing and the value “thing”. That’s why we can open an irb and do this:
irb(main):008:0> puts :myname myname => nil irb(main):009:0> :myname => :myname
Remember, symbols are not strings, therefore this is not possible:
irb(main):010:0> puts :myname + :othername NoMethodError: undefined method `+' for :myname:Symbol from (irb):10
Instead we can get the value of the symbol, and convert it to a String to get this:
irb(main):011:0> puts :myname.to_s + :othername.to_s mynameothername => nil
Very cute. So what’s the point?Symbols are mainly used to save memory. They have only one occurrence within a Ruby program, while strings with the same name are stored in different positions of memory every time. Check this:
irb(main):012:0> "string".object_id => 24125620 irb(main):013:0> "string".object_id => 24122170 irb(main):014:0> :string.object_id => 68258 irb(main):015:0* :string.object_id => 68258
And don’t forget that symbols are objects, just like everything in Ruby. They have a name and a string value, as we said, but an integer value to be recognized by the program as well, a value that is always constant. That brings many performance benefits (while comparing symbols, for example). They are like strings with a value that must not be changed.
Ruby on Rails screencasts
December 3, 2007
A fast post just to recommend a couple of links for those looking for Rails tutorials in video (screencasts).
For people yet not involved with Rails, the official Rails webpage gives somes good video examples on what is Rails about.
For people currently working with Rails we have the podcast Railscasts, which is constantly actualized and brings a new screencast every 10 days aprox.
And for people interested not only in the Rails framework, BestTechVideos provides technical videos about Ruby on Rails and other languages and frameworks.
Nice helper for testing model validation
December 3, 2007
I found this this morning in Mr. Matt’s blog. Is a fantastic helper method to save us work testing our ActiveRecord models validation, available under the Creative Commons Attribution 2.0 UK: England & Wales License.
# In test_helper.rb # Give this function an array of invalid values, an array of valid values, the object and # attribute name to test, and it will ensure that only valid values are allowed def validation_tester ( valid_values, invalid_values, attribute_name, test_object ) valid_values.each do |val| test_object.[]=(attribute_name, val) assert test_object.save, "#{attribute_name} should be valid: #{test_object.[](attribute_name)}" assert test_object.valid? assert !test_object.errors.invalid?(attribute_name) end invalid_values.each do |val| test_object.[]=(attribute_name, val) assert !test_object.save, "#{attribute_name} should NOT be valid: #{val}" assert !test_object.valid? assert test_object.errors.invalid?(attribute_name) end end
And is used as easy as this:
def test_email_validation valid_emails = ['matt@test.com', 'matt.hall@test.com', 'matt@test.ing.com', 'matt.hall@test.ing.com'] invalid_emails = ['@test.com', 'test.com', 'matt@', 'matt.hall@com', '.matt@test.ing.co.uk', 'matt@@test.com', '', '.@.'] u = create_user validation_tester( valid_emails, invalid_emails, 'email', u) end
Mocks and stubs in Ruby on Rails. The Mocha solution.
November 26, 2007
We know that we want our tests to be repeatable, simple and fast. Fast is the key word here. Some tests involve tasks that we don’t want to be run because they involve high time consumption. A classic example is trying to avoid the connection to the database when is not neccessary. This testing approach has lead to a whole framework called UnitRecord that allows us to test ActiveRecord models without hitting the database. This nicely wrapped gem makes use of stubs for faking database columns. But no so fast; let’s explain before what are stubs and mocks.
First of all should we point the difference (huge difference) between mocking and stubbing, as some times is not well understood. Stubs and mocks are similar concepts that drive to completely different testing philosophies, the classic TDD (Test Driven Development) and the fairly new BDD (Behaviour Driven Development).
On one hand, we would want to test our classes and methods by the results they give to us. If we have a method that takes an array of integers and returns it in ascendant order, we should consider writing a test which will take the array [4,3,5] and check that the result will be [3,4,5]. We don’t care about how our software do that, we care about whether what our software is giving as a result. This is classic TDD.On the other hand, we know that there are different algorithms for sorting an array. Maybe we were using an easy insertion sort algorithm, then we realised that the sets of numbers were getting bigger and bigger and decided to switch to a quick sort. The method is the same, the result as well, the way it does it is different. Testing our software paying attention at how it does it (and thus giving to the test cases our expectations on what the software is going to do in order to solve the task) is BDD.
A still-awake reader would have noticed that BBD involves highly coupled tests. A mock will have our expectations on the behaviour of the method declared, and our expectations will change every time we change the internal algorithm of our method. This is, I think, the biggest drawback of BDD and mocks. It has many advantages though, especially about the need to think about the design of our software from the very begging, when we are writing our test (yes, before start coding the real app), if you name correctly your tests cases, of course. BDD promotes also some good design techniques and autocomments the implementation code on the test (as we are describing there how our code works). Martin Fowler has an excellent article comparing advantages and disadvantages of both approaches, with some examples written in Java. And if you decide to go BDD, you should check RSpec for Ruby.If you still have to decide, we have in Ruby a marvellous tool that allows us to stub and mock with one single framework, called Mocha. RoR developers coming from Java will be happy as the syntax of Ruby Mocha is intended to be as close as possible to JMock. Here it is a brief test example of mocking:
def test_should_start_engine engine=mock('engine') car=Car.new(engine) engine.expects(:start) car.start end
And an example of stubbing with Mocha:
def test_should_return_false_for_failed_print document = stub("my document") document.stubs(:print).returns(false) ui = View.new(document) assert_equal false, ui.print end
Notice how in the first case we declare our expectations, while in the second case the assert the result of the test (this phase is called verification). We don’t have verification phase in BDD, thus we don’t have assertions.
Further reading
- James Mead, An Introduction To Mock Objects In Ruby, extracted from a presentation in the London Ruby Group.
- Mathew Williams, How I Learned to Stop Worrying And Love Web Application Testing.
- Bruce Tate, Mocking And Stubbing in Ruby On Rails. The example that Bruce uses to illustrate the difference between mocking and stubbing could be clearer, in my opinion.
- Ned Wolpert, Ruby Mocha.
NetBeans 6.0 Ruby Edition
November 20, 2007
For those who definitely don’t like the acclaimed TextMate when developing Ruby on Rails applications, chances were not very wide so far. We had RadRails, a RoR focused IDE, who showed off months ago as a promising working frame in its earliest versions, but has been lately reported that its developers have start loosing interest in improving it. We had also Eclipse, whose Ruby support has been also criticized.The finally we have since September the Ruby edition of the well-known NetBeans IDE. We have just installed it, so expect in the next day a comprehensive review. So far, it looks very promising. Let’s take a look at some of its advantages:
- Only 19Mb to download, a fair memory consumption and a lot of helpful functionality out of the box.
- It ships with code completion that works, extremely useful for those who never manage to learn by heart the rails framework. But also includes inline documentation just pressing CTRL + SPACE when typing a keyword.
- Rake support and generations of models, scaffolds, controllers… just in one click!
- Subversion integration to make your version control easier.
- Of course, a lot of helpful syntax highlighting and helpers.
- Built-in gem management!
- Run test on the IDE and RSpec support.
Here you can find a great review of the NetBeans IDE, from where I have stealed the screenshots. Also you have the screencasts of the official NetBeans website.