Learning Ruby notes

I’ve just finished my first plugin for Redmine, learning Ruby along the way.  It’s a bit messy, but it’s simple and does it’s job.  Some things that I learnt along the way:

When you’re in a view, <% tag is used for codes, and <%= is used to print the result of the codes to the screen.  For example:
<% issues = issues.sort_by {|issue| issue[‘date_relative’]} %> – sorts the array
<%= issues = issues.sort_by {|issue| issue[‘date_relative’]} %> – sorts the array and prints the output

debug and inspect are used for debugging; like so:
debug issues
issues.inspect
debug is a bit more useful, I found

Use .class to figure out the class the variable belongs to; in Ruby, arrays and hashes are classes as well, so it can be quite useful to find out what kind of data you’re looking at.

The output of debug can be confusing, for a long time I was trying to figure out why I couldn’t access some of the attributes of an array I was looking at.  I realised why after doing .count; there was one value in the array, and that array was an array containing the data I was trying to find (this is difficult to figure out from debug if you are using it for the first time).  So:
issue.value returned an error
issue[0].value was ok

It seems lots of RoR applications use ActiveRecords; this page is useful for further methods for debugging/accessing data: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
(In my case, Redmine classes are subclasses of ActiveRecord::Base)

Leave a Reply

Your email address will not be published. Required fields are marked *