<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-3883020610237687065</id><updated>2011-12-05T09:30:22.763Z</updated><title type='text'>Struggling With Ruby</title><subtitle type='html'>Documenting my experiences as I struggle to understand Ruby on Rails (Ruby version 1.8.6 tp 1.8.8, Rails version 2.1, to 2.2.2). See the &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page here&lt;/a&gt;.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>71</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-124043252498752602</id><published>2010-11-25T21:17:00.002Z</published><updated>2010-11-25T21:21:02.472Z</updated><title type='text'>Printing Labels</title><content type='html'>I recently had a need to print labels from our database. The factory produces samples; the idea is that they enter the samples into the database, which spits out a label to stick on it. Analysts then update the record as the results come in.&lt;br /&gt;&lt;br /&gt;After some rather lengthy discussions with my IT supplier we went for a Zebra GK420t label printer. The accompanying CD has a manual for programming in a language called ZPL, allowing me to set up my labels with complete flexibility.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Configuring a Printer Port&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I am in a Windows environment, and some of this is specific to Windows.&lt;br /&gt;&lt;br /&gt;The general strategy is to use Ruby to create a file, and then copy the file to the serial port. Most PCs nowadays do not have a serial port, but you can pretend the printer is on a serial port using the "net use" command at the DOS prompt. It is first necessary to share your printer on the network. Then, at the server where your project is run from, type something like this (comp01 is the computer's network name, zebra is the share name for the printer):&lt;br /&gt;&lt;pre&gt;net use lpt4 \\comp01\zebra /persistent:yes&lt;/pre&gt;&lt;br /&gt;You can check if the printer is still assigned to that port using "net use".&lt;br /&gt;&lt;br /&gt;If only it were that simple. Windows runs services in their own environment, so setting the printer at the prompt is great for when you are developing the project, as you run your web server from the command prompt. Then you go live, and now the project is run as a service on Tomcat or whatever, and has no clue about what you have done at the command prompt.&lt;br /&gt;&lt;br /&gt;The way I got around this was to put code into a file in config/initial, like this:&lt;br /&gt;&lt;pre&gt;printer = File.read('config/printer.cfg').strip&lt;br /&gt;command = "net use lpt4 \"#{printer}\""&lt;br /&gt;`net use lpt4 /delete`&lt;br /&gt;result = `#{command}`&lt;/pre&gt;&lt;br /&gt;Everytime Rails starts up, this reads the printer name from a file called config/printer.cfg, deletes the old setting and applies the new.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Printing&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Using the "copy" command, you can now send a file to the printer. I think it is useful to try that before getting into Ruby to ensure that works, so here is an example ZPL file (for labels 100x50 mm).&lt;br /&gt;&lt;pre&gt;^XA&lt;br /&gt;~SD15&lt;br /&gt;^LL200&lt;br /&gt;^PW750&lt;br /&gt;^FO50,60^ADN,36,40^FDMy first line^FS&lt;br /&gt;^FO50,110^ADN,36,20^FDA second line^FS&lt;br /&gt;^FO50,160^ADN,36,20^FDThe third line^FS&lt;br /&gt;^FO50,220^ADN,18,10^FDMy company^FS&lt;br /&gt;^FO50,245^ADN,18,10^FDCreated at 1847 on 13/Sep/10^FS&lt;br /&gt;^FO35,50^GB680,160,2^FS&lt;br /&gt;^XZ&lt;br /&gt;END&lt;/pre&gt;&lt;br /&gt;Here is some Ruby code that will generate a new file on the fly, and send it to the printer. Note that ZPL does not require that data is sent in the order in which it appears on the label.&lt;br /&gt;&lt;pre&gt;require 'date'&lt;br /&gt;&lt;br /&gt;class Printer&lt;br /&gt;PRINTER = 'lpt4'&lt;br /&gt;COMPANY = 'My Company Ltd'&lt;br /&gt;&lt;br /&gt;def self.print_label lines&lt;br /&gt;  # Accept either a string with line breaks embedded,&lt;br /&gt;  # or an array of strings&lt;br /&gt;  # (assume each line is not too long)&lt;br /&gt;  lines = lines.split("\n") if lines.is_a? String&lt;br /&gt;&lt;br /&gt;  # A "here document" defines the basic label,&lt;br /&gt;  # With a box, date and company name&lt;br /&gt;  text = &amp;lt;&amp;lt;-END&lt;br /&gt;    ^XA&lt;br /&gt;    ~SD15&lt;br /&gt;    ^LL200&lt;br /&gt;    ^PW750&lt;br /&gt;    ^FO50,#{70 + 50 * lines.length}^ADN,18,10^FD#{COMPANY}^FS&lt;br /&gt;    ^FO50,#{95 + 50 * lines.length}^ADN,18,10^FDCreated at #{DateTime.now.strftime('%H%M on %d/%b/%y')}^FS&lt;br /&gt;    ^FO35,50^GB680,#{10 + 50 * lines.length},2^FS&lt;br /&gt;    ^FO50,#{60}^ADN,36,40^FD#{lines[0]}^FS&lt;br /&gt;    END&lt;br /&gt;&lt;br /&gt;  # Each line sent is now added&lt;br /&gt;  (1..lines.length).each do |i|&lt;br /&gt;    text &amp;lt;&amp;lt; "^FO50,#{60 + 50 * i}^ADN,36,20^FD#{lines[i]}^FS\n"&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  # The file terminator is tagged on the end&lt;br /&gt;  text &amp;lt;&amp;lt; "^XZ"&lt;br /&gt;&lt;br /&gt;  # The file is created&lt;br /&gt;  File.open("print.txt", "w") { |file| file &amp;lt;&amp;lt; text }&lt;br /&gt;&lt;br /&gt;  # In Rails, stop at this point if in a unit test&lt;br /&gt;  return 'not printed' if RAILS_ENV == "test"&lt;br /&gt;&lt;br /&gt;  # Create a DOS command&lt;br /&gt;  command = "copy #{RAILS_ROOT}/print.txt #{PRINTER}"&lt;br /&gt;&lt;br /&gt;  # Usually Ruby will convert forward slashes to backslashes&lt;br /&gt;  # in Windows, but not here&lt;br /&gt;  command.gsub! '/', '\\'&lt;br /&gt;&lt;br /&gt;  # Use backticks for the system command&lt;br /&gt;  # so we can capture the output&lt;br /&gt;  result = `#{command}`&lt;br /&gt;&lt;br /&gt;  # Printed okay&lt;br /&gt;  return 'label printed' if result =~ /1 file\(s\) copied/&lt;br /&gt;&lt;br /&gt;  # Problem, so return the error message and command&lt;br /&gt;  "Label failed with error \"#{result}\", command was \"#{command}\""&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Printer.print_label ["My first line", "A second line", "The third line"]&lt;/pre&gt;&lt;br /&gt;You may want to consider whether two people might try to print at the same time. If the second writes a new file before the first has printed it, both users will get the second label. My understanding is that Rails handles one request at a time, so I do not think this is a problem, and for me, uses will only be printing from a single computer anyway.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-124043252498752602?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/124043252498752602/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=124043252498752602' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/124043252498752602'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/124043252498752602'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/11/printing-labels.html' title='Printing Labels'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4867154223337949850</id><published>2010-11-06T13:57:00.001Z</published><updated>2010-11-06T14:00:12.472Z</updated><title type='text'>Monkeybars, a UI framework</title><content type='html'>Finding a decent UI for use with Ruby is something of an on-going quest. I blogged a couple of years ago about &lt;a href="http://strugglingwithruby.blogspot.com/2008/09/ruby-gui.html"&gt;Ruby Shoes&lt;/a&gt;, which is a very neat idea, but is limited, and not really suited to big projects. I am not too sure how well it is being supported nowadays, though there is some activity at GitHub.&lt;br /&gt;&lt;br /&gt;So recently I was looking at Monkeybars. Monkeybars is not a UI as such, but a framework for using Swing inside an IDE. It attempts to hide all the underlying Java, so you just design your interface through your IDE, and the rest is Ruby (specially, JRuby of course, for Swing).&lt;br /&gt;&lt;br /&gt;There is a problem with Monkeybars; it does not work with recent versions of JRuby. I found an older version in an example file, and that works old (I have reported this as a bug &lt;a href="http://code.google.com/p/monkeybars-lib/issues/detail?id=32"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Installation&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Installing is simple (this will also install the "rawr" gem):&lt;br /&gt;&lt;pre&gt;gem install monkeybars&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Create a project&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;To create a new project:&lt;br /&gt;&lt;pre&gt;monkeybars my_project&lt;br /&gt;cd my_project&lt;br /&gt;rawr install&lt;/pre&gt;&lt;br /&gt;You than need to set it up in your IDE. Monkeybars was designed with NetBeans in mind, and that is the IDE I use too (it obviously needs both Ruby and Java included). It needs to be a Java project, as you are actually running a Java application that uses Ruby, so your new NetBeans project will be a "Java Project with Existing Sources". You need to point NetBeans to the source packages in the "my_project/src" folder. Once the project is created, right click on "Libraries" in the project browser, select "Add JAR/Folder" and select the .jar files in "my_project/lib/java".&lt;br /&gt;&lt;br /&gt;When you first run your project, NetBeans will ask for the main file; select "org.rubyforge.rawr.Main"&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Create your model-view-controller&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Just like Rails, you can use a rake task to generate these (in ths example, called "main"):&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;rake generate ALL=src/main&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This will generate the files:&lt;br /&gt;  * src/main/main_controller.rb&lt;br /&gt;  * src/main/main_view.rb&lt;br /&gt;  * src/main/main_model.rb&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Create the UI&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;You actually need a fourth file, which is the UI itself. In the IDE, right click on the folder (in this case "main") in the project browser, and select New - JFrame Form, and give it a suitable name (I chose MainJFrame). You can now add components graphically, using your IDE. The important point to remember is that any component you want your Ruby code to interact with should have a Ruby-friendly name. A "Quit" option on the file menu might be "quit_menu_item", but the menu itself you can leave to the default.&lt;br /&gt;&lt;br /&gt;To keep it simple, drag a label on to the dialog box, and set the variable name (found under the code tab) to "message".&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Edit the view&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The main_view.rb file is the glue between the Java UI and your Ruby code. The first thing it needs is the name of your Java UI. Then it needs to know how the components on the UI map (or more accurately, properties of the components) to the model. In this example, then we need only two lines.&lt;br /&gt;&lt;pre&gt;class MainView &amp;lt; ApplicationView&lt;br /&gt;set_java_class 'main.MainJFrame'&lt;br /&gt;map :model =&gt; :message, :view =&gt; "message.text"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can have as many map statements as you need, one for each component that displays data (not required for buttons, etc. that generate events only). The :view part means that one end of the link is to the text property of the JLabel that we called "message". The other end of the link is the message property in the model.&lt;br /&gt;&lt;br /&gt;You can set a mapping to be one way, by adding a :using value. In our example, the label cannot be edited directly by the user, so we only want the data to go from the model to the UI component, not the other way around (you can flip "nil" and ":default" to have the data go the other way only, but your model needs to provide read and write access to the property even so, because of the way Monkeybars creates a new model with the view data, then transfers data from that to the real model).&lt;br /&gt;&lt;pre&gt;map :model =&gt; :message, :view =&gt; "message.text", :using =&gt; [:default, nil]&lt;/pre&gt;&lt;br /&gt;You can also use the ":using" value to specify a method to convert the data; give the method name instead of :default.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Edit the controller&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The controller needs to be told the name of the model, and the name of the view. You can also set an action for when the dialog close is clicked. All of this is done for you, and is all we need for this simple application.&lt;br /&gt;&lt;pre&gt;class MainController &amp;lt; ApplicationController&lt;br /&gt;set_model 'MainModel'&lt;br /&gt;set_view 'MainView'&lt;br /&gt;set_close_action :exit&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;However, if you have any way for the user to interact with your dialog box, that gets captured here. Let us suppose you have a "Quit" option on yor file menu, and you have set the variable name to "quit_menu_item". This method will respond to that menu item being selected, and ask  for confirmation.&lt;br /&gt;&lt;pre&gt;def quit_menu_item_action_performed&lt;br /&gt;r = javax.swing.JOptionPane.showConfirmDialog(nil,&lt;br /&gt;          "Do you really want to quit?",&lt;br /&gt;          "Confirmation",&lt;br /&gt;          javax.swing.JOptionPane::YES_NO_OPTION,&lt;br /&gt;          javax.swing.JOptionPane::QUESTION_MESSAGE)&lt;br /&gt;exit if r == javax.swing.JOptionPane::YES_OPTION&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Here is another example for a button; the user presses the button and the text in two JTextAreas is used to update the model (the first JTextArea is called "text_area_1", but mapped to "text1" in the model, using  &lt;code&gt;map :model =&gt; :text1, :view =&gt; "text_area_1.text"&lt;/code&gt; in the view). The update_model method is used to transfer data to the model. Then the update method in the model is called (this is a method I have written, to do what I need in my model). Finally, update_view is called so the UI is updated to reflect the new state of the model.&lt;br /&gt;&lt;pre&gt;def update_button_action_performed&lt;br /&gt;model.text1 = view_state.model.text1&lt;br /&gt;model.text2 = view_state.model.text2&lt;br /&gt;model.update&lt;br /&gt;update_view&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;What happens is that calling view_state creates a new instance of the model, and this is populated with the values from the UI. You can then copy across the values you want into the real model. A convenience method, update_model, can be used instead.&lt;br /&gt;&lt;pre&gt;def update_button_action_performed&lt;br /&gt;update_model(view_state.model, :text1, text2)&lt;br /&gt;model.update&lt;br /&gt;update_view&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This is how the controller will handle most events, first transfer the data from the UI to the model, then call a method in the model, then update the view, so you could have one method to create a whole set.&lt;br /&gt;&lt;pre&gt;%w(up down edit cut paste insert).each do |action|&lt;br /&gt;%w(button menu_item).each do |type|&lt;br /&gt;  class_eval &amp;lt;&amp;lt;-"END"&lt;br /&gt;    def #{action}_#{type}_action_performed&lt;br /&gt;      model.text = view_state.model.text&lt;br /&gt;      model.#{action}&lt;br /&gt;      update_view&lt;br /&gt;    end&lt;br /&gt;  END&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can set the value for set_close_action to :nothing, :exit, :close, :dispose or :hide. If you want other functionality, override one of those methods in the controller (I found I could override close, but not exit).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Edit the model&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The model needs to include accessor methods for all the properties you mapped to in the view, and methods for all the actions. In our simple example, like this:&lt;br /&gt;&lt;pre&gt;attr_accessor :message&lt;/pre&gt;&lt;br /&gt;You can set properties through properly defined methods, but that is something of a minefield, I have found, and better avoided.&lt;br /&gt;&lt;br /&gt;There is no more to say about the model; Monkeybars makes no assumptions about it, and it has no parent class to inherit from (other than Object). This is where you do the real work.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4867154223337949850?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4867154223337949850/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4867154223337949850' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4867154223337949850'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4867154223337949850'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/11/monkeybars-ui-framework.html' title='Monkeybars, a UI framework'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5923597231387701679</id><published>2010-06-01T20:48:00.002+01:00</published><updated>2010-11-05T14:03:59.356Z</updated><title type='text'>Iterating through records</title><content type='html'>Occasionally, you want to be able to go through the records in a table one by one, i.e., from a page showing one record, you want to be able to jump to the next or previous record. One way I have seen to do this is with named_scopes. i like named_scopes, but really, they are not the solution in this case; a simple method for the model is more elegant. Compare:&lt;br /&gt;&lt;pre&gt;Post.forward(@post)[0]&lt;br /&gt;@post.forward&lt;/pre&gt;&lt;br /&gt;Note that a named_scope returns an array. Also, I have called the method forward, as next is a keyword in Ruby. Here are the two methods to go either way.&lt;br /&gt;&lt;pre&gt;def forward&lt;br /&gt; Post.find(:all, :conditions =&gt; ["id &gt; ?", id], :limit =&gt; 1, :order =&gt; "id ASC")[0]&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def back&lt;br /&gt; Post.find(:all, :conditions =&gt; ["id &lt; ?", id], :limit =&gt; 1, :order =&gt; "id DESC")[0]&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;If you want a looped list, you can use these two methods, which will loop around to other end of the list. They use the fact that nil is taken as false, and that Ruby uses lazy evaluation for Boolean arithmetic. he scond part of the expression is only evaulated if the first works out to be nil. There is also a random method, so you can jump around the list. I have made this a class method so you can also jump into a random point in the list.&lt;br /&gt;&lt;pre&gt;def forward&lt;br /&gt; Post.find(:all, :conditions =&gt; ["id &gt; ?", id], :limit =&gt; 1, :order =&gt; "id ASC")[0] || Post.find(:first, :order =&gt; "id ASC")&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def back&lt;br /&gt; Post.find(:all, :conditions =&gt; ["id &lt; ?", id], :limit =&gt; 1, :order =&gt; "id DESC")[0] || Post.find(:first, :order =&gt; "id DESC")&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.random&lt;br /&gt; Post.find(:first, :offset =&gt;rand(Post.count :all))&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;On your show view, add links like this:&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;&amp;lt;%= link_to 'Previous', :id =&gt; @post.back %&gt; |&lt;br /&gt;&amp;lt;%= link_to 'Random', :id =&gt; Post.random %&gt; |&lt;br /&gt;&amp;lt;%= link_to 'Next', :id =&gt; @post.forward %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5923597231387701679?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5923597231387701679/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5923597231387701679' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5923597231387701679'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5923597231387701679'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/06/iterating-through-records-occasionally.html' title='Iterating through records'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-3570004434985223851</id><published>2010-05-28T21:37:00.003+01:00</published><updated>2010-06-28T09:48:18.861+01:00</updated><title type='text'>Moving to Rails 2.3.8</title><content type='html'>I have recently decided to move to Rails version 2.3.8. I have tried rails 2.3 a while ago, but it did not agree with JRuby. As JRuby 1.5 is now available, I thought I should give it another go. Though I had the same problem, I fixed it this time.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;application_controller.rb&lt;/strong&gt;&lt;br /&gt;The first change is that app/application.rb must be renamed to app/application_controller.rb, which certainly makes it more consistent.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;JRuby and Rake&lt;/strong&gt;&lt;br /&gt;I think this was the issue that stopped my moving to 2.3.2. Running any rake command that accesses the database (and, for example, the test tasks invoke database tasks, so will do this as well) generates this:&lt;br /&gt;&lt;pre&gt;rake aborted!&lt;br /&gt;Task not supported by 'jdbcpostgresql'&lt;/pre&gt;&lt;br /&gt;The problem seems to have been know about two years ago (see &lt;a href="http://dev.rubyonrails.org/ticket/11596"&gt;here&lt;/a&gt;; more recently &lt;a href="http://old.nabble.com/-jira--Created:-%28JRUBY-4550%29-jruby-1.4.0-lib-ruby-gems-1.8-gems-rails-2.3.5-lib-tasks-databases.rake-expects-%22postgresql,%22-not-%22jdbcpostgresql%22-td27525838.html"&gt;here&lt;/a&gt;). When Rake has to interact with the database, it checks the hash generated from your database.yml file, and finds the adapter is called &lt;code&gt;jdbcpostgresql&lt;/code&gt;. It then compares this against the adapters it knows, trying - and failing - to match &lt;code&gt;postgresql&lt;/code&gt;. The solution is to edit the rakes file that handles database interactions (rails-2.3.8\lib\tasks/databases.rake) and change every occurance of &lt;code&gt;"postgresql"&lt;/code&gt; or &lt;code&gt;'postgresql'&lt;/code&gt; (with quotes) to &lt;code&gt;/postgresql/&lt;/code&gt;. Now it will sucessfully match the jdbc adapter. Obviously if you are using another database, you need to change it for that.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Is test_helper loaded twice?&lt;/strong&gt;&lt;br /&gt;I have a couple of constants defined in test/test_helper.rb, and this causes warning that they have already been defined. I can only assume this is because the file is getting loaded twice, but I could not see why that might be the case.&lt;br /&gt;&lt;br /&gt;Also in test/test_helper.rb, you need to change:&lt;br /&gt;&lt;pre&gt;class Test::Unit::TestCase&lt;/pre&gt;&lt;br /&gt;... to:&lt;br /&gt;&lt;pre&gt;class ActiveSupport::TestCase&lt;/pre&gt;&lt;br /&gt;Otherwise, you will get "&lt;code&gt;undefined method `use_transactional_fixtures=' &lt;/code&gt;"&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Deprecation warnings&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;"Giving :session_key to SessionStore is deprecated, please use :key instead."&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In config/environment.rb, change :secret_key to :key. It will look something like this:&lt;br /&gt;&lt;pre&gt;config.action_controller.session = {&lt;br /&gt;:key =&gt; '_AuthSampleLog_session',&lt;br /&gt;:secret      =&gt; #some big hex number&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;"Using assert_redirected_to with partial hash arguments is deprecated"&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Usually, your redirect will specify a controller and an action, but occasionally you specify something else as well, such as an id. Now in Rails &lt;code&gt;assert_redirected_to&lt;/code&gt; checks each of the key-value pairs that you specify (this is confusing because the API says they are all optional; considered with &lt;code&gt;redirect_to&lt;/code&gt; they are option; they just have to match up).&lt;br /&gt;&lt;br /&gt;So this is fine, because the test specifies the controller and the action.&lt;br /&gt;# In the controller&lt;br /&gt;redirect_to :controller =&gt; :audits, :action =&gt; :edit&lt;br /&gt;# In the controller test&lt;br /&gt;assert_redirected_to :controller =&gt; :audits, :action =&gt; :edit&lt;br /&gt;&lt;br /&gt;In this case, the test must also specify the id, because it is given in the redirect_to.&lt;br /&gt;# In the controller&lt;br /&gt;redirect_to :controller =&gt; :audits, :action =&gt; :edit, :id =&gt; @audit_section.audit_id&lt;br /&gt;# In the controller test&lt;br /&gt;assert_redirected_to :controller =&gt; :audits, :action =&gt; :edit, :id =&gt; as.audit_id&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Integration testing&lt;/strong&gt;&lt;br /&gt;I found some odd things happened with logging out in my integration tests; eventually isolated this to a known bug:&lt;br /&gt;https://rails.lighthouseapp.com/projects/8994/tickets/2200-session-support-broken&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-3570004434985223851?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/3570004434985223851/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=3570004434985223851' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3570004434985223851'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3570004434985223851'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/05/moving-to-rails-238.html' title='Moving to Rails 2.3.8'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-1233455576059780027</id><published>2010-05-02T22:04:00.000+01:00</published><updated>2010-05-02T22:05:19.421+01:00</updated><title type='text'>Ruby Unit Testing</title><content type='html'>Ruby has a built-in unit testing facility, &lt;code&gt;Test::Unit&lt;/code&gt;. To use it, create a new file, and define a class that inherits from &lt;code&gt;Test::Unit::TestCase&lt;/code&gt;. This is best done in a separate folder, by the way, so you can easily release your project without the unit tests (Rails sets this all up for yu by the way).&lt;br /&gt;&lt;pre&gt;# Load in the unit test classes&lt;br /&gt;require 'test/unit'&lt;br /&gt;# Load in your class to be tested&lt;br /&gt;require 'things'&lt;br /&gt;&lt;br /&gt;class ThingsTest &amp;lt; Test::Unit::TestCase&lt;br /&gt;&lt;br /&gt; def setup&lt;br /&gt;   # Set up some test conditions here&lt;br /&gt;   # This will be invoked before each test&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def teardown&lt;br /&gt;   # This will be invoked after each test&lt;br /&gt;   # Use to close connections, etc.&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You will also need to define your tests. Each test goes in its own method, the name of which must begin "test" (as Ruby will search your class for such methods for testing).&lt;br /&gt;&lt;pre&gt;def test_thing_creates_okay&lt;br /&gt; # assertions&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;There are several assertions you can use to test the results. Here are some of the more common ones:&lt;br /&gt;&lt;pre&gt;assert_equal      # Compares two objects&lt;br /&gt;assert            # Tests for true&lt;br /&gt;assert_nil        # Tests for nil&lt;br /&gt;assert_raise      # Tests an exception is thrown&lt;br /&gt;assert_in_delta   # Test two floats are within a given amount&lt;/pre&gt;&lt;br /&gt;Rails (since about 2.2) uses a different format for tests:&lt;br /&gt;&lt;pre&gt;test "Thing creates okay" do&lt;br /&gt; # assertions&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The end result is the same. In Rails, &lt;code&gt;test&lt;/code&gt; is a method that dynaally defines a method (in this case called "test_thing_creates_okay") with the given block.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Running Tests&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;If you are using NetBeans you can run a test simply by right clicking on the file being tested, and selecting test. NetBeans can work out which the relevant test is as long as it is named conventionally (eg the test for things.rb would be things_test.rb). Alternatively, you can right click on the test file, and selecting test or run.&lt;br /&gt;&lt;br /&gt;To test from the command prompt, simply run the test file through ruby (eg &lt;code&gt;ruby things_test.rb&lt;/code&gt;; if you are using JRuby, do &lt;code&gt;jruby things_test.rb&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;For a big project, you can collect all your tests together to form a test suite. Just create a Ruby file that requires each of the tests in turn, and run that through Ruby. Alternativerly, put this in your test suite, and it will automatically go though every file in that folder that has a name ending "_test.rb".&lt;br /&gt;&lt;pre&gt;files = Dir.entries(File.dirname(__FILE__)).select do |file|&lt;br /&gt; file =~ /_test.rb$/&lt;br /&gt;end&lt;br /&gt;files.each { |file| require file }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Testing private methods and variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Here is a trivial class with an instance variable and a private method.&lt;br /&gt;&lt;pre&gt;class UnitTestee&lt;br /&gt; def initialize x&lt;br /&gt;   @val = x&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; private&lt;br /&gt;&lt;br /&gt; def do_stuff y&lt;br /&gt;   @val * @val * y&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I can test the private method using send, like this:&lt;br /&gt;&lt;pre&gt;def test_do_stuff&lt;br /&gt; @ut = UnitTestee.new 12&lt;br /&gt; assert_equal 12 * 12 * 5, @ut.send(:do_stuff, 5)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Note that I have left Ruby to calculate 12 * 12 * 5; not only does this save me doing it, it makes it clearer where the number comes from (even better to use named constants, of course).&lt;br /&gt;&lt;br /&gt;To access the instance variable, I can define a new method. Doing that in my test file means that the new method is not part of the API. Here is one way to do it (there are others):&lt;br /&gt;&lt;pre&gt;def test_variable&lt;br /&gt; @ut = UnitTestee.new 12&lt;br /&gt; eval "def @ut.get_val; @val; end"&lt;br /&gt; assert_equal 12, @ut.get_val&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Note&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Test files often include something like this at the start:&lt;br /&gt;&lt;pre&gt;$:.unshift File.join(File.dirname(__FILE__),'..','lib')&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This simply adds the code folder (called "lib" here) to the load path, so Ruby can find the file to be tested.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-1233455576059780027?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/1233455576059780027/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=1233455576059780027' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1233455576059780027'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1233455576059780027'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/05/ruby-unit-testing.html' title='Ruby Unit Testing'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4713022478160759457</id><published>2010-05-01T20:30:00.000+01:00</published><updated>2010-05-01T20:31:13.102+01:00</updated><title type='text'>Using partials as methods</title><content type='html'>Most of my models have an associated view that lists the records on the index page. Rails generates the code, so generally I do not worry about it, but if I am doing the same thing across a dozen models/controllers, surely it would be better to just do it once? Actually, I am not sure. You do not save any typing, as Rails generates the views (assuming you are in the habit of specifying all your columns from the start), and it is less readable this way. Anyway, let us look at how it can be done, and you can decide for yourself if it is worth while or not.&lt;br /&gt;&lt;br /&gt;The way to achieve this is through a partial. Conceptually a partial is just a method that returns a chuck of HTML code You send it a few parameters mapped to the :local key, it processes your code, and returns the HTML. I want my partial accessible from any view, so I created a new folder, app/views/shared, with a partial called _table.rhtml.&lt;br /&gt;&lt;br /&gt;I will be invoking my table from within a view with something like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;%=&lt;br /&gt;  render :partial =&gt; 'shared/table', :locals =&gt; {&lt;br /&gt;    :list =&gt; SamplesHelper::WORKSHEET_LIST,&lt;br /&gt;    :data =&gt; @worksheets,&lt;br /&gt;    :links =&gt; check_role?('analyst') ? :edit : :show,&lt;br /&gt;  }&lt;br /&gt;%&gt;&lt;/pre&gt;&lt;br /&gt;The render method is sent a hash with a :partial key that maps to the location of the file (without the underscore), and a :locals key with my parameters. This is the standard procedures for partils. Within locals I have chosen to require three parameters that will define how the table is drawn. The first, :data, is simply an array of ActiveRecord::Base objects, that is, the database records that Rails got for me.&lt;br /&gt;&lt;br /&gt;The :links parameter determines whether the user sees links to show, to show and edit, or to show, edit and destroy. In this case, I am checking if the user has the "analyst" role; if he does, I want the edit and show links, otherwise just the show links.&lt;br /&gt;&lt;br /&gt;Finally, the :list parameter is an array of hashes, which I chose to define in a helper file, and which might look like this:&lt;br /&gt;&lt;pre&gt;WORKSHEET_LIST = [&lt;br /&gt;  {:heading =&gt; "Date", :column =&gt; "created_at.format_date"},&lt;br /&gt;  {:heading =&gt; "Type", :column =&gt; :name},&lt;br /&gt;  {:heading =&gt; "Sample", :column =&gt; :sample.number},&lt;br /&gt;]&lt;/pre&gt;&lt;br /&gt;This will give me three columns, with the given headings, and the values from the given columns (or rather, method calls). Note that the first is a symbol, the others are strings. This will be explained later.&lt;br /&gt;&lt;br /&gt;My partial looks like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;table align="center"&gt;&lt;br /&gt;  &amp;lt;tr&gt;&lt;br /&gt;    &amp;lt;% list.each do |item| %&gt;&lt;br /&gt;      &amp;lt;th&gt;&amp;lt;%= item[:heading] %&gt;&amp;lt;/th&gt;&lt;br /&gt;    &amp;lt;% end %&gt;&lt;br /&gt;    &amp;lt;th colspan="&amp;lt;%= [:none, :show, :exit, :destroy].index(links) %&gt;"&gt; &amp;lt;/th&gt;&lt;br /&gt;  &amp;lt;/tr&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;% for datum in data %&gt;&lt;br /&gt;  &amp;lt;tr class="&amp;lt;%= cycle('odd', 'even') %&gt;"&gt;&lt;br /&gt;    &amp;lt;% list.each do |item| %&gt;&lt;br /&gt;      &amp;lt;td&gt;&amp;lt;%= item[:column].is_a?(Symbol) ? h(datum.send(item[:column])) : eval("datum.#{item[:column]}") %&gt;&amp;lt;/td&gt;&lt;br /&gt;    &amp;lt;% end %&gt;&lt;br /&gt;    &amp;lt;td&gt;&amp;lt;%= link_to 'Show', { :action =&gt; :show, :id =&gt; datum.id } %&gt;&amp;lt;/td&gt;&lt;br /&gt;    &amp;lt;% unless links == :show %&gt;&lt;br /&gt;      &amp;lt;td&gt;&amp;lt;%= link_to 'Edit', { :action =&gt; :edit, :id =&gt; datum.id } %&gt;&amp;lt;/td&gt;&lt;br /&gt;    &amp;lt;% end %&gt;&lt;br /&gt;    &amp;lt;% if links == :destroy %&gt;&lt;br /&gt;      &amp;lt;td&gt;&amp;lt;%= link_to 'Destroy', { :action =&gt; :destroy, :id =&gt; datum.id }, :confirm =&gt; 'Are you sure?', :method =&gt; :delete %&gt;&amp;lt;/td&gt;&lt;br /&gt;    &amp;lt;% end %&gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;/tr&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;br /&gt;&amp;lt;/table&gt;&lt;/pre&gt;&lt;br /&gt;For the headings, it iterates through the list, pulling out the :heading value. Then it iterates over the records, and for each record again iterates through the list, this time pulling out the column value. If the :column value is a symbol, the send method is invoked, and the output HTML-escaped. If the :column value is a string, an eval is performed, allowing you to do something more involved (in the example, format a date). Note that this is not HTML-escaped; I have methods that return HTML strings to, for example, highlight values a certain colour, so this preserves that feature. However, you should consider carefully if this is safe in your situation. Note that I coud have defined a formated_created_at method in my model, and invoked that method using a symbol, rather than "created_at.format_date".&lt;br /&gt;&lt;br /&gt;The table pads out the headings over the links at the right, and adds only those links that are requested.&lt;br /&gt;&lt;br /&gt;As an aside, I was surprised to find that the parameters you send in the :locals hash really are local variables; I expected them to be method calls, like the supposed variables for columns in ActiveRecord.&lt;br /&gt;&lt;br /&gt;I added a section at the top of the page that verifies the parameters are there. It just throws an exception if a required parameter is missing, and defines a default for the :links value should that one be missing.&lt;br /&gt;&lt;pre&gt;&amp;lt;%&lt;br /&gt;  raise RuntimeError.new("list not set for _form") unless defined? list&lt;br /&gt;  raise RuntimeError.new("data not set for _form") unless defined? data&lt;br /&gt;&lt;br /&gt;  links = :show unless defined? links&lt;br /&gt;%&gt;&lt;/pre&gt;&lt;br /&gt;I think it is important to document your partial, so anyone using it knows what he has to supply in the way of parameters.&lt;br /&gt;&lt;pre&gt;&amp;lt;%#&lt;br /&gt;This partial must be sent:&lt;br /&gt;- an array of hashes called "list"&lt;br /&gt;- an array of ActiveRecords in "data"; the records from the database&lt;br /&gt;&lt;br /&gt;It can also be sent:&lt;br /&gt;- a value, "links" set to one of: :edit, :show, :destroy (defaults to :show)&lt;br /&gt;&lt;br /&gt;The hashes in the array "list" must have a :heading key and a :column key.&lt;br /&gt;The :heading key should map to a string, giving the column name.&lt;br /&gt;The :column key should map to a symbol or string.&lt;br /&gt;If a symbol, then that will be used the send method on the record, and the&lt;br /&gt;output with be HTML-escaped; use this for model column names.&lt;br /&gt;If a string is supplied, it will be used in an eval&lt;br /&gt;method call, and the output will not be HTML-escaped.&lt;br /&gt;%&gt;&lt;/pre&gt;&lt;br /&gt;The last thing to do is to test your partial. This needs to be done as a functional test, because you need the infrastructure that that implies. This means we need a new action, let us call it &lt;code&gt;_render&lt;/code&gt;, which can be defined in the ApplicationController class (but in the test_helper.rb file, so it only exists in your tests). The action firstly executes a string, params[:eval], which would set up any instance variables required for your test. The page is then rendered, using the partial as defined in params[:args].&lt;br /&gt;&lt;pre&gt;class ApplicationController&lt;br /&gt;  def _render&lt;br /&gt;    eval(params[:eval]) unless params[:eval].nil?&lt;br /&gt;    render :inline =&gt; "&lt;%= render #{params[:args]} %&gt;"&lt;br /&gt;  end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You should create a new file with your other functional tests. You need to tell Rails which controller it will use (should be okay to use any of them), using the &lt;code&gt;tests&lt;/code&gt; method. You may need to load in some records (or you can use fixtures), and you may need to log in.&lt;br /&gt;&lt;br /&gt;The meat of the test is the &lt;code&gt;get&lt;/code&gt; command, invoking the &lt;code&gt;_render&lt;/code&gt; action defined before, with two arguments, the parameters for the partial, and the code for grabbing some ActiveRecords to show (both as strings, please note).&lt;br /&gt;&lt;pre&gt;class PartialTest &amp;lt; ActionController::TestCase&lt;br /&gt;  tests ChembaseRefsController&lt;br /&gt;&lt;br /&gt;  def test_table&lt;br /&gt;    load_sample_records&lt;br /&gt;    login_as 'librarian', @request&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    get :_render, :args =&gt; ":partial =&gt; 'shared/table', :locals =&gt; {&lt;br /&gt;      :list =&gt; ChembaseRefsHelper::REFS_LIST,&lt;br /&gt;      :data =&gt; @chembase_refs,&lt;br /&gt;      :links =&gt; :destroy,&lt;br /&gt;    }", :eval =&gt; "@chembase_refs = ChembaseRef.find :all"&lt;br /&gt;&lt;br /&gt;    doc = REXML::Document.new @response.body&lt;br /&gt;    assert_equal ChembaseRef.count(:all) + 1, doc.elements.to_a("table/tr").length#, "#{@response.body}\n"&lt;br /&gt;    assert_equal ChembaseRefsHelper::REFS_LIST.length + 1, doc.elements.to_a("table/tr/th").length#, "#{@response.body}\n"&lt;br /&gt;  end&lt;/pre&gt;&lt;br /&gt;The method ends by creating an XML document from the respoonse, and testing the number of columns and rows are what they should be.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4713022478160759457?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4713022478160759457/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4713022478160759457' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4713022478160759457'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4713022478160759457'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/05/using-partials-as-methods.html' title='Using partials as methods'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-6482909094654036606</id><published>2010-04-24T08:52:00.003+01:00</published><updated>2010-11-05T14:20:17.423Z</updated><title type='text'>Operator Overloading</title><content type='html'>Ruby permits operator overloading, allowing you to define how operators will work with your own (or indeed any) classes. Here is a quick example, showing how to define the addition operator. Note that you get the &lt;code&gt;+=&lt;/code&gt; for free.&lt;br /&gt;&lt;pre&gt;class Tester1&lt;br /&gt; def initialize x&lt;br /&gt;   @x = x&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def +(y)&lt;br /&gt;   @x + y&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;a = Tester1.new 5&lt;br /&gt;puts(a + 3)&lt;br /&gt;# =&gt; 8&lt;br /&gt;a += 7&lt;br /&gt;puts a&lt;br /&gt;# =&gt; 12&lt;/pre&gt;&lt;br /&gt;The definition is not commutative, i.e., trying to do &lt;code&gt;3 + a&lt;/code&gt; would fail. To get that to work you would need to override the addition method in Integer - and I think that would be a bad idea.&lt;br /&gt;&lt;br /&gt;The next example shows how to override comparison operators. Note that by overriding the equality operator, you get the inequality operator for free. Also note that you are not restricted to returning a boolean; in this example &lt;code&gt;&amp;lt;=&lt;/code&gt; returns a string.&lt;br /&gt;&lt;pre&gt;class Tester2&lt;br /&gt; def initialize ary&lt;br /&gt;   @ary = ary&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; attr_reader :ary&lt;br /&gt;&lt;br /&gt; def ==(y)&lt;br /&gt;   @ary.length == y.ary.length&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def &amp;lt;(y)&lt;br /&gt;   @ary.length &amp;lt; y.ary.length&lt;br /&gt; end&lt;br /&gt; def &amp;lt;=(y)&lt;br /&gt;   '@ary.length &amp;lt; y.ary.length'&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;b = Tester2.new %w(zero one two three)&lt;br /&gt;puts b == Tester2.new([1, 2, 3, 4, 5])&lt;br /&gt;# =&gt; false&lt;br /&gt;puts b != Tester2.new([1, 2, 3, 4, 5])&lt;br /&gt;# =&gt; true&lt;br /&gt;puts b &amp;lt; Tester2.new([1, 2, 3, 4, 5])&lt;br /&gt;# =&gt; true&lt;br /&gt;puts b &amp;lt;= Tester2.new([1, 2, 3, 4, 5])&lt;br /&gt;# =&gt; "@ary.length &amp;lt; y.ary.length"&lt;/pre&gt;&lt;br /&gt;You need to be careful when overriding operators, as it has the potential to make your code unfathomable. One time I think it is particular useful, however, is to add array-like properties to a class, for example to access an underlying array, as in this example. Note how the &lt;code&gt;+=&lt;/code&gt; operator has to be defined via the + operator. Also, the index operator needs two methods if you want to be able to both read from and write to it.&lt;br /&gt;&lt;pre&gt;class Tester3&lt;br /&gt; def initialize ary&lt;br /&gt;   @ary = ary&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def [](y)&lt;br /&gt;   @ary[y]&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def []=(y, value)&lt;br /&gt;   @ary[y] = value&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def &amp;lt;&amp;lt;(y)&lt;br /&gt;   @ary &amp;lt;&amp;lt; y&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; def +(y)&lt;br /&gt;   @ary &amp;lt;&amp;lt; y&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;c = Tester3.new %w(zero one two three)&lt;br /&gt;puts c[3]&lt;br /&gt;# =&gt; three&lt;br /&gt;c &amp;lt;&amp;lt; 'four'&lt;br /&gt;puts c[4]&lt;br /&gt;# =&gt; four&lt;br /&gt;c += 'five'&lt;br /&gt;puts c[5]&lt;br /&gt;# =&gt; five&lt;/pre&gt;&lt;br /&gt;As an aside, be aware that &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; and &lt;code&gt;+=&lt;/code&gt; are not the same for an Array object (though they are for Tester3). The &lt;code&gt;+=&lt;/code&gt; operator requires an array, the members of which are added to the existing array. The &lt;code&gt;&amp;lt;&amp;lt;&lt;/code&gt; operator appends the new object to the array; if the new object is an array, you have the new array nested inside the existing array.&lt;br /&gt;&lt;br /&gt;You cannot override keywords, such as "or", nor can you override:&lt;br /&gt;&lt;pre&gt;&amp;amp;&amp;amp; &amp;amp; || | () {} :: . ~ .. ...&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-6482909094654036606?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/6482909094654036606/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=6482909094654036606' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6482909094654036606'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6482909094654036606'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/04/operator-overloading.html' title='Operator Overloading'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-1369131401983964302</id><published>2010-04-20T18:17:00.001+01:00</published><updated>2010-04-20T18:18:51.797+01:00</updated><title type='text'>XML and Ruby</title><content type='html'>When you come back to XML after using &lt;a href="http://strugglingwithruby.blogspot.com/2008/10/yaml.html"&gt;YAML&lt;/a&gt;, it is a real pain in the neck. However, sometime we have to do it.&lt;br /&gt;&lt;br /&gt;REXML offers a comprehensive set of functions for negotiating an XML document, so this is what I used to read an XML document into a Ruby data structure.&lt;br /&gt;&lt;br /&gt;First, the setting up. Load in the REXML library, and include it for convenience. Load in the XML file.&lt;br /&gt;&lt;pre&gt;require "rexml/document"&lt;br /&gt;include REXML&lt;br /&gt;&lt;br /&gt;file = File.new("materials.xml")&lt;br /&gt;doc = REXML::Document.new file&lt;/pre&gt;&lt;br /&gt;In my XML, &lt;code&gt;materials&lt;/code&gt; in the root node, and this has a number of children, &lt;code&gt;msds&lt;/code&gt;, which in turn have a number of children, &lt;code&gt;material&lt;/code&gt;. Each &lt;code&gt;material&lt;/code&gt; node has a set of attributes, plus some child nodes of its own.&lt;br /&gt;&lt;br /&gt;Each element has an &lt;code&gt;attributes&lt;/code&gt; attribute and an &lt;code&gt;elements&lt;/code&gt; attribute. You can iterate though these using each, but you can also select specific nodes by sending a path to the each method. I want to start by iterating through the msds nodes:&lt;br /&gt;&lt;pre&gt;doc.elements.each("materials/msds") do |msds|&lt;br /&gt; # do stuff&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;For each iteration though the loop, I then need to go though that elements nodes with an inener loop.&lt;br /&gt;&lt;br /&gt;For the material nodes, I need to go though the attributes. The &lt;code&gt;each&lt;/code&gt; method of &lt;code&gt;attributes&lt;/code&gt; has two parameters for the block, the name and value. Easy to add these to a hash (&lt;code&gt;material_data&lt;/code&gt;).&lt;br /&gt;&lt;pre&gt;material.attributes.each do |name, value|&lt;br /&gt; material_data[name.to_sym] = value&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;To extract specific values from a node, into a hash, I did this:&lt;br /&gt;&lt;pre&gt;h = { :name =&gt; element.text,&lt;br /&gt;     :type =&gt; element.name,&lt;br /&gt;     :file =&gt; element.attributes["file"] }&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;text&lt;/code&gt; method gets the inner text from the element, &lt;code&gt;name&lt;/code&gt; gives the tag name, and &lt;code&gt;attributes["file"]&lt;/code&gt; gets the value of the "file" attribute.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;require "rexml/document"&lt;br /&gt;include REXML&lt;br /&gt;&lt;br /&gt;file = File.new("materials.xml")&lt;br /&gt;doc = REXML::Document.new file&lt;br /&gt;&lt;br /&gt;data = []&lt;br /&gt;&lt;br /&gt;doc.elements.each("materials/msds") do |msds|&lt;br /&gt; msds_data = []&lt;br /&gt; msds.elements.each("material") do |material|&lt;br /&gt;   material_data_ary = []&lt;br /&gt;   material.elements.each do |element|&lt;br /&gt;     h = { :name =&gt; element.text,&lt;br /&gt;           :type =&gt; element.name,&lt;br /&gt;           :file =&gt; element.attributes["file"] }&lt;br /&gt;&lt;br /&gt;     material_data_ary &lt;&lt; material_data =" {" msds =""&gt; material_data_ary }&lt;br /&gt;   material.attributes.each {|name, value| material_data[name.to_sym] = value }&lt;br /&gt;&lt;br /&gt;   msds_data &lt;&lt; msds =""&gt; msds_data, :file =&gt; msds.attributes["file"] }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;REXML API&lt;br /&gt;&lt;a href="http://www.germane-software.com/software/rexml/doc/"&gt;http://www.germane-software.com/software/rexml/doc/&lt;/a&gt;&lt;br /&gt;Tutorial&lt;br /&gt;&lt;a href="http://www.germane-software.com/software/rexml/docs/tutorial.html"&gt;http://www.germane-software.com/software/rexml/docs/tutorial.html&lt;/a&gt;&lt;br /&gt;Further&lt;br /&gt;&lt;a href="http://www.developer.com/lang/article.php/3672621"&gt;http://www.developer.com/lang/article.php/3672621&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-1369131401983964302?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/1369131401983964302/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=1369131401983964302' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1369131401983964302'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1369131401983964302'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/04/xml-and-ruby.html' title='XML and Ruby'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-732702159719941659</id><published>2010-04-01T19:18:00.002+01:00</published><updated>2010-11-05T14:20:45.577Z</updated><title type='text'>Testing for Valid HTML</title><content type='html'>There is a gem for testing valid HTML called &lt;a href="http://agilewebdevelopment.com/plugins/railstidy"&gt;RailsTidy&lt;/a&gt;, however, when I tried to use it I got "RuntimeError: can't find the symbol `tidyCreate' ", which seems to relate to calling non-Ruby code (possibly failing because I am using JRuby?). So anyway, I looked at doing my own.&lt;br /&gt;&lt;br /&gt;The best way to approach this is to create a method that works like the usual &lt;code&gt;assert_x&lt;/code&gt; methods, so it can be invoked like this:&lt;br /&gt;&lt;pre&gt;def test_should_get_index&lt;br /&gt; get :index&lt;br /&gt; assert_response :success&lt;br /&gt; assert_not_nil assigns(:posts)&lt;br /&gt; &lt;b&gt;assert_validates&lt;/b&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The skeleton of my method is going to look like this:&lt;br /&gt;&lt;pre&gt;def assert_validates message = ''&lt;br /&gt; clean_backtrace do&lt;br /&gt;   msg = build_message(message, "Invalid HTML found")&lt;br /&gt;   assert_block(msg) do&lt;br /&gt;     # Code here&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;In common with other &lt;code&gt;assert_x&lt;/code&gt; methods, it will accept an optional message. The &lt;code&gt;clean_backtrace&lt;/code&gt; method does what it says. It catches &lt;code&gt;AssertionFailedErrors&lt;/code&gt;, cleans the backtrace, and rethrows the error. I am using it to ensure backtraces from my method are consistent with the backtrace from other such methods.&lt;br /&gt;&lt;br /&gt;Inside that block, I use the &lt;code&gt;assert_block&lt;/code&gt; method. This is the workhorse of all assertions; it catches and counts failures and errors, based on what happens inside its block. If it returns true, the test passes. One limitation here is that it seems impossible to modify the message from within the block, so we can report back what the problem was.&lt;br /&gt;&lt;br /&gt;Now to check the HTML is valid. I am going to cheat here, and actually check that it is valid XML, as then I can palm the work off on REXML (remember the require "rexml/document").&lt;br /&gt;&lt;pre&gt;begin&lt;br /&gt; REXML::Document.new @response.body&lt;br /&gt; true&lt;br /&gt;rescue REXML::ParseException =&gt; ex&lt;br /&gt; false&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The code attempts to create an XML document from the body of the response. The block returns true if this was fine, and false if REXML threw an exception. You could put a print statement in there tto indicate where the problem is; I prefered to run any offending page through a proper validator (eg &lt;a href="http://validator.w3.org/check"&gt;here&lt;/a&gt; or href="http://htmlhelp.com/cgi-bin/validate.cgi"&gt;here) once a problem is found, as it tells you exactly what it is.&lt;br /&gt;&lt;br /&gt;Here is the whole thing, which should be inside &lt;code&gt;ActiveSupport::TestCase&lt;/code&gt;, in &lt;code&gt;test_helper.rb&lt;/code&gt;. I have added a constant, so you can turn validation on or off.&lt;br /&gt;&lt;pre&gt;require "rexml/document"&lt;br /&gt;&lt;br /&gt;# Do you want to validate?&lt;br /&gt;VALIDATE = true&lt;br /&gt;&lt;br /&gt;def assert_validates message = ''&lt;br /&gt; # Do not bother if validation is turned off&lt;br /&gt; return unless VALIDATE&lt;br /&gt; # Do not bother unless it is actually HTML&lt;br /&gt; return unless @response.content_type == "text/html"&lt;br /&gt;&lt;br /&gt; clean_backtrace do&lt;br /&gt;   assert_block(build_message(message, "Invalid HTML found")) do&lt;br /&gt;     begin&lt;br /&gt;       REXML::Document.new @response.body&lt;br /&gt;       true&lt;br /&gt;     rescue REXML::ParseException =&gt; ex&lt;br /&gt;       puts ex&lt;br /&gt;       false&lt;br /&gt;     end&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can check a whole bunch of tests in one file by adding a teardown method, like this.&lt;br /&gt;&lt;pre&gt;def teardown&lt;br /&gt; assert_validates&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;If an action results in a redirect, this will only test that the redirect directive is valid HTML, not that the page the user is sent to is. That page is not generated during a functional test (though it will be if another action returns that page, and you test that action).&lt;br /&gt;&lt;br /&gt;You could put the &lt;code&gt;assert_validates&lt;/code&gt; method into a module, and include that module in both &lt;code&gt;ActiveSupport::TestCase&lt;/code&gt; and &lt;code&gt;ActionController::Integration::Session&lt;/code&gt;. This would allow you to validate in your integration tests too. I am not sure that that actually has any benefit; you would seem to be testing the same thing twice.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-732702159719941659?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/732702159719941659/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=732702159719941659' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/732702159719941659'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/732702159719941659'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/04/testing-for-valid-html.html' title='Testing for Valid HTML'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-6074122482970419986</id><published>2010-03-31T20:09:00.002+01:00</published><updated>2010-05-13T11:56:24.266+01:00</updated><title type='text'>Variables</title><content type='html'>In Ruby (as in most OO languages) there are four sort of variables; global, class, instance and local. In languages like Java and C++, you must declare a variable before use, and where you do that determines what sort it is. In Ruby, variables are not declared, so we need another way to indicate this; a prefix.&lt;br /&gt;&lt;br /&gt;Variables can contain any object in Ruby; you can readily assign a string to a variable that previously held an integer. Variable names must begin with a lower-case letter or underscore (after the prefix). By convention, they are all lower-case, with words separated by underscores (eg my_variable).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Local Variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Local variables have no prefix. They exist only within a block of code, such as a method. Once the block completes, the variable disappears.&lt;br /&gt;&lt;pre&gt;def test2&lt;br /&gt;local1 = 2&lt;br /&gt;local1.times do&lt;br /&gt;local2 = 3&lt;br /&gt;p "l1=#{local1} l2=#{local2}"&lt;br /&gt;end&lt;br /&gt;p "l1=#{local1}"&lt;br /&gt;#p "l2=#{local2}"  # Out of scope&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Instance Variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;An instance variable belongs to that one instance of the class. It is denoted by a single &lt;i&gt;at&lt;/i&gt; symbol (eg &lt;code&gt;@var&lt;/code&gt;), and can be accessed from any instance of a class from within a method. They have private access... however, you can access them anyway through these methods:&lt;br /&gt;&lt;pre&gt;instance_variables    # Array of strings, listing instance variables&lt;br /&gt;instance_variable_defined?&lt;br /&gt;instance_variable_set&lt;br /&gt;instance_variable_get&lt;br /&gt;remove_instance_variable  # Private method&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can also use &lt;code&gt;attr_accessor&lt;/code&gt;, &lt;code&gt;attr_reader&lt;/code&gt; and &lt;code&gt;attr_writer&lt;/code&gt; to allow others to access your instance variables. Note that while the above methods do require the &lt;i&gt;at&lt;/i&gt; sign, these three methods do not.&lt;br /&gt;&lt;br /&gt;You can also access instance variables using self. These two statements are equivalent.&lt;br /&gt;&lt;pre&gt;self.var = 19&lt;br /&gt;@var = 19&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Class Variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;A class variable belongs to the whole class (and indeed subclasses), and is accessible from anywhere inside the class, or from any instance of the class. If you change the value in one instance, it will be changed in every instance. It must start with two &lt;i&gt;at&lt;/i&gt; symbols (eg &lt;code&gt;@@var&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;In Rails, you can access a class variable like a class method (eg &lt;code&gt;MyClass.var&lt;/code&gt;) for a descendant of &lt;code&gt;ActiveRecord::Base&lt;/code&gt; (analogous to how you access column names). Outside Rails class variables have private access.&lt;br /&gt;&lt;br /&gt;Class variables have some perhaps surprising behavior when you look at inheritance, as a value set in a subclass can affect other classes. Let us see that in action. &lt;code&gt;SubClass1&lt;/code&gt; has a parent, &lt;code&gt;SuperClass&lt;/code&gt;, a sibling, &lt;code&gt;SubClass2&lt;/code&gt;, and a child &lt;code&gt;SubSubClass1&lt;/code&gt;.&lt;br /&gt;&lt;pre&gt;class SuperClass&lt;br /&gt;@@var1 = 11&lt;br /&gt;@@var2 = 21&lt;br /&gt;def self.out1; @@var1; end&lt;br /&gt;def self.out2; @@var2; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class SubClass1 &lt; var1 =" 12" var3 =" 31" var1 =" 13" var3 =" 32" var2 =" 22"&gt; 13&lt;br /&gt;p SubClass1.out1&lt;br /&gt;# =&gt; 13&lt;br /&gt;p SubClass2.out1&lt;br /&gt;# =&gt; 13&lt;br /&gt;&lt;br /&gt;# @var2 is in the top class and its grandchild class. Despite "skipping&lt;br /&gt;# a generation", the value set in the sub-sub-class still affects the&lt;br /&gt;# super-class&lt;br /&gt;p SuperClass.out2&lt;br /&gt;# =&gt; 22&lt;br /&gt;p SubSubClass1.out2&lt;br /&gt;# =&gt; 22&lt;br /&gt;&lt;br /&gt;# @var3 is in the sibling classes only, not in a common super-class. In this&lt;br /&gt;# case setting the value in one has no effect on the other.&lt;br /&gt;p SubClass1.out3&lt;br /&gt;# =&gt; 31&lt;br /&gt;p SubClass2.out3&lt;br /&gt;# =&gt; 32&lt;/pre&gt;&lt;br /&gt;There are a set of methods available to use class variables, analogous to those for instance variables.&lt;br /&gt;&lt;pre&gt;class_variables    # Array of strings, listing instance variables&lt;br /&gt;class_variable_defined?&lt;br /&gt;class_variable_set&lt;br /&gt;class_variable_get&lt;br /&gt;remove_class_variable  # Private method&lt;/pre&gt;&lt;br /&gt;In Rails, you can define setters and getters just as you can for instance variables; &lt;code&gt;cattr_accessor&lt;/code&gt;, &lt;code&gt;cattr_reader&lt;/code&gt; and &lt;code&gt;cattr_writer&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Global Variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;A global variable must start with a &lt;i&gt;dollar&lt;/i&gt; (eg &lt;code&gt;$var&lt;/code&gt;). It accessible from any class at any time. They are generally regarded as something to avoid; better to keep sections of code isolated from each other as far as possible.&lt;br /&gt;&lt;br /&gt;Ruby has a number of predefined global variables. I do not like to use them myself; they make code that much harder to understand, and where there is a more explicit alternative, I would always use that. However, there is a list &lt;a href="http://www.zenspider.com/Languages/Ruby/QuickRef.html#18"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;There is an interesting trace feature for global variables. The &lt;code&gt;trace_var&lt;/code&gt; method takes either a string or a symbol representing the global variable (with the dollar sign), together with a &lt;code&gt;proc&lt;/code&gt; object (the documentation claims it will take a string or block as well; I do not believe that that is true).&lt;br /&gt;&lt;pre&gt;trace_var "$global_var", proc do |x|&lt;br /&gt;puts "$global_var is now #{x}"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can set more than one trace on a global variable, and you can remove them (all) with &lt;code&gt;untrace_var&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;global_variables&lt;/code&gt; method will return an array of strings, the names of all the global variables (complete with dollar sign).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Special Variables&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Ruby includes a handful of special variables:&lt;br /&gt;&lt;pre&gt;self     # "this" in Java, etc.&lt;br /&gt;true&lt;br /&gt;false&lt;br /&gt;nil      # "null" in Java, etc., also counts as false&lt;br /&gt;__FILE__ # the current file&lt;br /&gt;__LINE__ # the current line number.&lt;/pre&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;All Together Now&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Let us them all in action. Here is some sample code.&lt;br /&gt;&lt;pre&gt;$global_var = 32&lt;br /&gt;&lt;br /&gt;class TestClass&lt;br /&gt;@@class_var = 14&lt;br /&gt;&lt;br /&gt;def initialize&lt;br /&gt;@instance_var = 20&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def test&lt;br /&gt;local_var = 7&lt;br /&gt;$global_var += 1&lt;br /&gt;@@class_var += 1&lt;br /&gt;@instance_var += 1&lt;br /&gt;local_var += 1&lt;br /&gt;puts "$global_var=#{$global_var}"&lt;br /&gt;puts "@@class_var=#{@@class_var}"&lt;br /&gt;puts "@instance_var=#{@instance_var}"&lt;br /&gt;puts "local_var=#{local_var}"&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Both &lt;code&gt;$global_var&lt;/code&gt; and &lt;code&gt;@@class_var&lt;/code&gt; are set when the file is loaded. While &lt;code&gt;$global_var&lt;/code&gt; is available to everything, &lt;code&gt;@@class_var&lt;/code&gt; can only be accessed from within &lt;code&gt;TestClass&lt;/code&gt;. Looking at &lt;code&gt;@instance_var&lt;/code&gt;, this will be set to 20 for a specific instance of &lt;code&gt;TestClass&lt;/code&gt; when the instance is created. It will be incremented whenever test is invoked on that instance, in contrast to &lt;code&gt;$global_var&lt;/code&gt; and &lt;code&gt;@@class_var&lt;/code&gt;, both of which will get incremented every time test is invoked on &lt;i&gt;any&lt;/i&gt; instance. Finally, &lt;code&gt;local_var&lt;/code&gt; is created when it is set in the test method, and destroyed when the method terminates.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-6074122482970419986?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/6074122482970419986/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=6074122482970419986' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6074122482970419986'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6074122482970419986'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/03/variables.html' title='Variables'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-3513130963457248958</id><published>2010-03-18T20:45:00.002Z</published><updated>2010-03-18T21:08:47.391Z</updated><title type='text'>Capturing File Uploads</title><content type='html'>Here is the requirement: The web page asks the user to upload a file. The data in the file is then used to populate a new record in the database.&lt;br /&gt;&lt;br /&gt;The first thing I want, then, is for the view to have a file upload button. Here is what worked for me:&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag 'create', :multipart =&gt; true do %&gt;&lt;br /&gt;&amp;lt;%= hidden_field_tag :sample_id, @sample.id %&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;&amp;lt;%= file_field_tag 'datafile' %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;File names can only contain numbers, letters, hyphens and underscores, and must end ".csv".&lt;br /&gt;Files must be on your C: drive to be successfully uploaded.&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;&amp;lt;%= submit_tag "Okay" %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;/pre&gt;&lt;br /&gt;You could also use the &lt;code&gt;form_for&lt;/code&gt; method instead, with &lt;code&gt;file_field&lt;/code&gt;, rather than &lt;code&gt;file_field_tag&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Some points to note:&lt;br /&gt;&lt;br /&gt;You need to flag the form as "multipart", so that the file gets submitted as one part, and other data on the form as a second part. My experience is that uploaded files are a little restricted, and will not upload from a networked drive, or if there are strange characters in the name, and I warn the user of this. This may be dependant on your system. In this particular case, I am looking for a .csv file. The file type may need to be defined as a MIME type (CSV is registed by default).&lt;br /&gt;&lt;br /&gt;The file received is of the &lt;code&gt;UploadedTempfile&lt;/code&gt; type, and seems to be useable like any other file. As far as I can tell, Rails closes and deletes it for you. It is accessible though &lt;code&gt;params&lt;/code&gt; in the normal way (so as &lt;code&gt;params[:datafile]&lt;/code&gt; from the above code).&lt;br /&gt;&lt;pre&gt;params[:datafile].each_line do |s|&lt;br /&gt;# do stuff&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I could not find away to process a CSV file using the CSV library; it seems to demand a filename, rather than the file itself. I was obliged to do it by hand (in my case I knew every field would be surrounded by quotes, so it is pretty easy).&lt;br /&gt;&lt;br /&gt;In the functional test, just send the file as a parameter (with a test file in the fixtures folder).&lt;br /&gt;&lt;pre&gt;post :create, :sample_id =&gt; Sample.find(:first).id,&lt;br /&gt;   :datafile =&gt; File.new("#{RAILS_ROOT}/test/fixtures/results.csv")&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-3513130963457248958?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/3513130963457248958/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=3513130963457248958' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3513130963457248958'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3513130963457248958'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/03/capturing-file-uploads.html' title='Capturing File Uploads'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5995382484081210113</id><published>2010-03-11T21:18:00.002Z</published><updated>2010-03-11T21:21:14.872Z</updated><title type='text'>Rails: Singularize and Pluralize</title><content type='html'>Rails has functions buit-in that will turn a word into its plural or singular. It uses this when generating models, etc. to create names that conform to the standard (so &lt;code&gt;user.rb&lt;/code&gt; but &lt;code&gt;users_controller.rb&lt;/code&gt;). The rules are set up in a file called:&lt;br /&gt;&lt;pre&gt;...\lib\ruby\gems\1.8\gems\activesupport-2.3.2\lib\active_support\inflections.rb&lt;/pre&gt;&lt;br /&gt;The action all happened inside a block like this:&lt;br /&gt;&lt;pre&gt;module ActiveSupport&lt;br /&gt; Inflector.inflections do |inflect|&lt;br /&gt;   # definitions&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;There are four types of rules. The first sets a general rule for making a plural, like this:&lt;br /&gt;&lt;pre&gt;inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')&lt;/pre&gt;&lt;br /&gt;If the regular expression in the first parameter matches, then it is replaced by the the second parameter (but note that a capture group is used, so a part of the discarded ending is still used). This rule will match a word ending in y, but not preceded by a vowel, replacing the "y" with "ies"&lt;br /&gt;&lt;br /&gt;The second sets a rule for making a singluar, like this (which is the reverse of the previous):&lt;br /&gt;&lt;pre&gt;inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')&lt;/pre&gt;&lt;br /&gt;Then there are the irregulars, defined like this:&lt;br /&gt;&lt;pre&gt;inflect.irregular('person', 'people')&lt;/pre&gt;&lt;br /&gt;And those that do not change, like this: &lt;br /&gt;&lt;pre&gt;inflect.uncountable(%w(equipment information rice money species series fish sheep))&lt;/pre&gt;&lt;br /&gt;Unfortunately, it is not perfect (not in 2.3.3 anyway), which is why I was obliged to learn about it. For example:&lt;br /&gt;&lt;pre&gt;inflect.plural(/(octop|vir)us$/i, '\1i')&lt;/pre&gt;&lt;br /&gt;The plural of virus is viruses, not viri; octopus can use either form, though octopuses is prefered (see &lt;a href="http://en.wikipedia.org/wiki/Plural_form_of_words_ending_in_-us"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;The particular one I ran up against was this, for "metal analyses":&lt;br /&gt;&lt;pre&gt;inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '\1\2sis')&lt;br /&gt;inflect.singular(/(^analy)ses$/i, '\1sis')&lt;/pre&gt;&lt;br /&gt;The system runs through the rules starting with the last defined, until it finds a match. For "analyses", it hits the second of the lines shown above, and returns "analysis" (why this was not put in as an irregular I cannot imagine). There is no match there for "metal analysis" as the pattern specifies the start of the string. So it looks at the previous rule. Now a match is found. However, this match defines several capture groups, the first is "analy", the second is just the "a", and both these are used in the replacement, so the resulting plural goes like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;whatever was before the pattern&gt; &amp;lt;"analy"&gt; &amp;lt;"a"&gt; &amp;lt;"sis"&gt;&lt;br /&gt;&lt;br /&gt;"metal analyses -&gt; metal analy&lt;span style="font-weight: bold;"&gt;a&lt;/span&gt;sis&lt;/pre&gt;&lt;br /&gt;Because the replacement uses only the first and second capture groups, the other words in that rule work fine. For "theses", for example, the "t" is in capture group 8, which is not used. And as analysis on its own gets caught by the previous rule, the error can easily be missed.&lt;br /&gt;&lt;br /&gt;This issue was bought up as a bug, but dismissed (see &lt;a href="https://rails.lighthouseapp.com/projects/8995-rails-plugins/tickets/28-activesupport-inflections-rb-incorrect-singularization-of-ses-to-sis-words#ticket-28-5"&gt;here&lt;/a&gt;). The simple workaround is to define your own rule. I have done this in a file inside config/initializers (I have called mine called initial.rb).&lt;br /&gt;&lt;pre&gt;ActiveSupport::Inflector.inflections do |inflect|&lt;br /&gt; inflect.singular(/(analy|ba|diagno|parenthe|progno|synop|the)ses$/i, '\1sis')&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can add as many of your own rules as you like. As they get added later, they will take precedence over the existing rules.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5995382484081210113?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5995382484081210113/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5995382484081210113' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5995382484081210113'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5995382484081210113'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/03/rails-singularize-and-pluralize.html' title='Rails: Singularize and Pluralize'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7448817974353432419</id><published>2010-03-04T18:19:00.002Z</published><updated>2010-03-04T18:27:25.476Z</updated><title type='text'>Adventures in programming...</title><content type='html'>Back in the day I used to love text-based adventure games (the one that stands out is Leather Goddesses of Phobos). I have made several attempts to write my own, in various languages from BASIC, to C, to Java. The use of an object-orientated language like Java was a big help, but I was recently wondering how Ruby might work (whether it will even come to anything is dubious).&lt;br /&gt;&lt;br /&gt;Ruby has a number of apparent advantages, and a consideration of how the data file might be illustrates that.&lt;br /&gt;&lt;pre&gt;def setup&lt;br /&gt; locations = [&lt;br /&gt;   Location.new(:id =&gt; :start, :name =&gt; 'The Start', :south =&gt; :hall,&lt;br /&gt;                :north =&gt; :lobby),&lt;br /&gt;   Location.new(:id =&gt; :hall, :name =&gt; 'The Great Hall', :north =&gt; :lobby),&lt;br /&gt;   Location.new(:id =&gt; :lobby, :name =&gt; 'The Swanky Lobby', :south =&gt; :hall),&lt;br /&gt; ]&lt;br /&gt; items = [&lt;br /&gt;   Item.new(:id =&gt; :sword, :name =&gt; "Widowmaker Sword", :loc =&gt; :hall),&lt;br /&gt;   Item.new(:id =&gt; :robes, :name =&gt; "Magical Robes", :loc =&gt; :lobby,&lt;br /&gt;            :wearable =&gt; true),&lt;br /&gt;   Item.new(:id =&gt; :health, :name =&gt; "Healing Potion", :loc =&gt; :hall,&lt;br /&gt;            :consume =&gt; "He gained 5 hit points.&lt;% @char[:health] += 5 %&gt;"),&lt;br /&gt; ]&lt;br /&gt; characters = [&lt;br /&gt;   Character.new(:id =&gt; :boris, :name =&gt; 'Boris', :location =&gt; 'Home',&lt;br /&gt;                 :inv_limit =&gt; 2, :health =&gt; 5),&lt;br /&gt; ]&lt;br /&gt; commands = [&lt;br /&gt;     {:verb =&gt; :take_from, :alias =&gt; [/^take ([\w ]+) from (\w+)$/,&lt;br /&gt;                                      /^take ([\w ]+) out of (\w+)$/,&lt;br /&gt;                                      /^remove ([\w ]+) from (\w+)$/],&lt;br /&gt;       :item_not_here =&gt; "It's not there."&lt;br /&gt;     },&lt;br /&gt;     {:verb =&gt; :get, :alias =&gt;       [/^get ([\w ]+)$/,&lt;br /&gt;                                      /^take ([\w ]+)$/,&lt;br /&gt;                                      /^pick up ([\w ]+)$/],&lt;br /&gt;       :okay =&gt; "+char+ picked up +item+.",&lt;br /&gt;       :item_not_here =&gt; "It's not there.",&lt;br /&gt;       :inv_limit =&gt; "You're holding enough already.",&lt;br /&gt;       :cannot_get_static =&gt; "You can't get that!"&lt;br /&gt;     },&lt;br /&gt;     {:verb =&gt; :examine, :alias =&gt;   [/^examine ([\w ]+)$/,&lt;br /&gt;                                      /^look at ([\w ]+)$/,&lt;br /&gt;                                      /^describe ([\w ]+)$/],&lt;br /&gt;       :item_not_present =&gt; "It's not here.",&lt;br /&gt;     },&lt;br /&gt;     {:verb =&gt; :simple_com, :alias =&gt; [/^look$/],&lt;br /&gt;       :script =&gt; "&lt;%= @location.describe %&gt;",&lt;br /&gt;     },&lt;br /&gt; ]&lt;br /&gt; World.new locations, items, characters, commands&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Data files are code&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In all my previous attempts, my data files have been simple text files (perhaps in XML). This time I took the example of Rails; migrations, the routes files and rake files are all Ruby code, so there is far more you can put in there when you configure. Previously I have had to write code just to load my data; not so this time.&lt;br /&gt;&lt;br /&gt;It should be easy to extend the system, even in run time. Create a new data file, perhaps with code to modify existing locations, and run it as a script.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Hashes&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Ruby just asks for you to use hashes for pretty much everything (again, Rails does this a lot). They are so easy to create, to use and to pass around. Sure, Java has hashes too, but it never encouraged me to use them (so really this is only an apparent advantage).&lt;br /&gt;&lt;br /&gt;At its simplest, you just make everything, whether the player, an item or the location, a hash, and give it the values appropriate. Want to add a new property? Just add a new value to the relevant hashes and away you go.&lt;br /&gt;&lt;br /&gt;Want to save the data? In one line you can save an array of hashes to YAML, and load it back in in another line.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Regular Expressions&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;For understanding what the user is saying, regular expressions are so useful. An input like "&lt;span style="font-style: italic;"&gt;put the cat in the bag&lt;/span&gt;" can readily be matched against &lt;code&gt;/^put ([\s ])+ in ([\s ])$/&lt;/code&gt;, and straight away you can pull out what went in where (regular expressions have been in Java since 1.4; too late for when I was trying to use it).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Dynamic Method Calls&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Once the command has been recognised, the appropriate method can be invoked simply by calling send, with the :verb value from the hash. Could be done using reflection in Java, but not as easy. Earlier languages... no way.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Scripts&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;With Ruby a scripting language, it is easy to just put scripts into the hashes. In the healing potion above, an ERB script is used to restore health.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7448817974353432419?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7448817974353432419/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7448817974353432419' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7448817974353432419'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7448817974353432419'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/03/adventures-in-programming.html' title='Adventures in programming...'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-2328560799477098549</id><published>2010-03-03T17:26:00.002Z</published><updated>2010-03-03T17:31:13.998Z</updated><title type='text'>Ruby Sockets</title><content type='html'>I was messing around with Ruby sockets, and came up with a simple chat-server. Testing proved to be rather more complicated... If you run this program, you can connect to it using "telnet &lt;server name="" or="" ip="" address=""&gt; 6606".&lt;br /&gt;&lt;pre&gt;require 'socket'&lt;br /&gt;require 'thread'&lt;br /&gt;&lt;br /&gt;# Boardcaster maintains a list of users.&lt;br /&gt;class Broadcaster&lt;br /&gt; def initialize; @users = []; end&lt;br /&gt; def add user; @users &lt;&lt; socket =" TCPServer.open(6606)" broadcaster =" Broadcaster.new" lock =" Mutex.new"&gt;")&lt;br /&gt;   user = {:name =&gt; s.gets.strip, :socket =&gt; s }&lt;br /&gt;   b.add user&lt;br /&gt;   print("#{user[:name]} is accepted\n")&lt;br /&gt;   s.write("Hello #{user[:name]}\n\rUsers on-line: #{b.list}\n\r&gt;")&lt;br /&gt;   while true&lt;br /&gt;     st = s.gets.strip&lt;br /&gt;     #p st&lt;br /&gt;     break if st == 'bye'&lt;br /&gt;     lock.synchronize do&lt;br /&gt;       b.broadcast "#{user[:name]} says \"#{st}\"\n\r&gt;"&lt;br /&gt;     end&lt;br /&gt;   end&lt;br /&gt;   lock.synchronize do&lt;br /&gt;     b.broadcast "#{user[:name]} has left\n\r&gt;"&lt;br /&gt;   end&lt;br /&gt;   s.close&lt;br /&gt;   b.remove user&lt;br /&gt;   print("#{user[:name]} is gone\n")&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This was my first experience of both threads and sockets on Ruby, and with regards to threads, I have to admit to being pretty clueless! However, it does seem worthwhile locking the shared resource, b, when used on a thread.&lt;br /&gt;&lt;br /&gt;Sockets seems straightforward enough. A new socket is opened using the TCPServer class. Data is collected with gets, and sent with write. At the end it is closed. I suspect there should be some exception handling in there, but it certainly proves the concept.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Testing Stream-Handling Methods&lt;br /&gt;&lt;br /&gt;Okay, so now I want to test my methods that handle streams. Let us suppose that you have a method that accepts data from some stream and outputs to another, like the broadcast method above, and you want to test it. How do you do it?&lt;br /&gt;&lt;br /&gt;First, let me simplify, and instead consider this method:&lt;br /&gt;&lt;pre&gt;def get_data source, sink&lt;br /&gt; print "\n&gt;"&lt;br /&gt; name = source.gets.strip&lt;br /&gt; print "\n&gt;"&lt;br /&gt; age = source.gets.strip&lt;br /&gt; sink.print "Name: #{name}, age: #{age}"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This could be invoked for use with the keyboard like this&lt;br /&gt;&lt;pre&gt;get_data $stdin, $stdout&lt;/pre&gt;&lt;br /&gt;Or across a network, like this:&lt;br /&gt;&lt;pre&gt;require 'socket'&lt;br /&gt;socket = TCPServer.open(6606)&lt;br /&gt;get_data socket, socket&lt;/pre&gt;&lt;br /&gt;If I want to test that method the trick is to use StringIO objects.&lt;br /&gt;&lt;pre&gt;def test_get_data1&lt;br /&gt; StringIO.open { |sink|&lt;br /&gt;   get_data(StringIO.new("Boris\n32\n"), sink)&lt;br /&gt;   assert_equal "Name: Boris, age: 32", sink.string&lt;br /&gt; }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Actually, Ruby would happily let you use the same StringIO object for both input and output, but the output would be appended to the input string, so your assertion would need to check for both the input and the output.&lt;br /&gt;&lt;pre&gt;def test_get_data2&lt;br /&gt; StringIO.open("Boris\n32\n") { |io|&lt;br /&gt;   get_data(io, io)&lt;br /&gt;   assert_equal "Boris\n32\nName: Boris, age: 32", io.string&lt;br /&gt; }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;That is bad; if we change the get_data method to accept different input, we would need to change the test in two places, and that is clearly a bad thing. Well, okay, we change it so the input gets inserted into what we expect. The problem now is that Ruby is modifying that string during the test, so we need instead to give Ruby a duplicate of the input string for it to play with, so we still have the orignal for comparison at the end.&lt;br /&gt;&lt;pre&gt;def test_get_data3&lt;br /&gt; input = "Boris\n32\n"&lt;br /&gt; StringIO.open(input.clone) { |io|&lt;br /&gt;   get_data(io, io)&lt;br /&gt;   assert_equal "#{input}Name: Boris, age: 32", io.string&lt;br /&gt; }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Then again, perhaps we need to rethink. The whole thing can be generalised into a new method, which can test any method against any input. The test itself can then be reduced to a single line.&lt;br /&gt;&lt;pre&gt;def test_get_data4&lt;br /&gt; stream_test("Boris\n32\n", "Name: Boris, age: 32") do |io|&lt;br /&gt;   get_data(io, io)&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def stream_test input, output&lt;br /&gt; StringIO.open(input.clone) { |io|&lt;br /&gt;   yield io&lt;br /&gt;   assert_equal "#{input}#{output}", io.string&lt;br /&gt; }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;A serious problem with all of these is that errors do not get caught by the test regime. A message is sent to the output, but the error is not counted in the totals (failures, on the other hand, are). I guess this is because the redirect is capturing the exception. A way around this is to capture the exception inside the block, and then flag this as a failure:&lt;br /&gt;&lt;pre&gt;def stream_test input, output&lt;br /&gt; StringIO.open(input.clone) { |io|&lt;br /&gt;   begin&lt;br /&gt;     yield io&lt;br /&gt;   rescue Exception =&gt; ex&lt;br /&gt;     assert false, "ERROR: #{ex.inspect}\n#{$!.backtrace[0..12] * "\n"}"&lt;br /&gt;   end&lt;br /&gt;   assert_equal "#{input}#{output}", io.string&lt;br /&gt; }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Testing Multiple Threads&lt;br /&gt;&lt;br /&gt;Those tests are all very well, but my Broadcast object sends messages to multiple users. How do I test that? Now I need threads in my tests!&lt;br /&gt;&lt;br /&gt;Here is a test method that worked for me:&lt;br /&gt;&lt;pre&gt;def test_broadcast&lt;br /&gt; # SETTING UP&lt;br /&gt;&lt;br /&gt; # The number of threads to spawn&lt;br /&gt; number = 100&lt;br /&gt; test_string = 'teststring'&lt;br /&gt; b = Broadcaster.new&lt;br /&gt; # Define strings outside the blocks so we can access them&lt;br /&gt; # later on&lt;br /&gt; string_ary = Array.new(number, '')&lt;br /&gt; thread_ary = Array.new(number)&lt;br /&gt; main_s = nil&lt;br /&gt;&lt;br /&gt; # LISTENING THREADS&lt;br /&gt; # A number of threads are spawned, they listen for&lt;br /&gt; # messages for 0.2 seconds, then write their StringIO&lt;br /&gt; # string to string_ary, before terminating.&lt;br /&gt;&lt;br /&gt; number.times do |i|&lt;br /&gt;   # Spawn a new thread&lt;br /&gt;   thread_ary[i] = Thread.start(b, i) do&lt;br /&gt;     # Create a StringIO object to collect the string&lt;br /&gt;     StringIO.open do |sink|&lt;br /&gt;       # Create a new user, and add it to the Broadcaster&lt;br /&gt;       user = {:name =&gt; 'test1', :socket =&gt; sink }&lt;br /&gt;       b.add user&lt;br /&gt;       # Wait a short time for the message to be broadcast&lt;br /&gt;       # Choose wisely, 0.2 on my system led to failures&lt;br /&gt;       sleep(0.3)&lt;br /&gt;       # Set s1 to a copy of the sink string, so it&lt;br /&gt;       # is still around outside the block&lt;br /&gt;       string_ary[i] = sink.string.clone&lt;br /&gt;     end&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; # SENDING THREAD&lt;br /&gt; # On the main thread, this sends the message, then waits&lt;br /&gt; # for all the other threads to terminate.&lt;br /&gt;&lt;br /&gt; # Create a StringIO object to collect the string&lt;br /&gt; StringIO.open do |sink|&lt;br /&gt;   begin&lt;br /&gt;     # Create a new user, and add it to the Broadcaster&lt;br /&gt;     user = {:name =&gt; 'test2', :socket =&gt; sink }&lt;br /&gt;     b.add user&lt;br /&gt;     # Broadcast the test string&lt;br /&gt;     b.broadcast(test_string)&lt;br /&gt;     # Wait for the other threads to finish&lt;br /&gt;     # by which time the broadcast should have been received.&lt;br /&gt;     number.times { |i| thread_ary[i].join }&lt;br /&gt;     main_s = sink.string.clone&lt;br /&gt;   rescue Exception =&gt; ex&lt;br /&gt;     # Flag any exceptions as a failure&lt;br /&gt;     assert false, ex.inspect&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; # TESTING&lt;br /&gt; # Test all the threads received the test_string&lt;br /&gt; assert_equal test_string, main_s&lt;br /&gt; number.times { |i| assert_equal test_string, string_ary[i] }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;/server&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-2328560799477098549?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/2328560799477098549/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=2328560799477098549' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2328560799477098549'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2328560799477098549'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/03/ruby-sockets.html' title='Ruby Sockets'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5099329003230193199</id><published>2010-01-30T12:32:00.002Z</published><updated>2010-01-30T13:10:56.657Z</updated><title type='text'>Using Java Applets</title><content type='html'>I had a system that I wanted to create where the user could do some complicated manipulation of data, before sending the results to the database. It seemed to me that a Java applet would be the best way to interface with the user, but how to interface the applet with Rails?&lt;br /&gt;&lt;br /&gt;The applet itself was very straightforward. It picks up the initial data from two parameters, rt and pc (each a list of floats, combining to make pairs of data). I also needed a public class that would return the results in a string.&lt;br /&gt;&lt;pre&gt;package railsapplet;&lt;br /&gt;&lt;br /&gt;public class MyApplet extends javax.swing.JApplet {&lt;br /&gt;  MyData data;&lt;br /&gt;&lt;br /&gt;  @Override&lt;br /&gt;  public void init() {&lt;br /&gt;      String rt = getParameter("rt");&lt;br /&gt;      String pc = getParameter("pc");&lt;br /&gt;      data = new MyData(rt, pc);&lt;br /&gt;      // Set up UI&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  // etc.&lt;br /&gt;&lt;br /&gt;  public String getOutput() {&lt;br /&gt;      return data.getOutput();&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;I packaged my Java in a jar file, insides public/applets. My view needed to reference that applet.&lt;br /&gt;&lt;pre&gt;&amp;lt;applet codebase="http://&amp;lt;%= ApplicationController::SITE %&gt;/applets"&lt;br /&gt;      width="400" height="400"&lt;br /&gt;      code="railsapplet.MyApplet.class" archive="railsapplet.jar"&lt;br /&gt;      name="myapplet"&lt;br /&gt;      id="myapplet"&lt;br /&gt;      align="center"&gt;&lt;br /&gt;&amp;lt;param name="rt" value="&lt;%= @rt.join(" ") %&gt;"&gt;&lt;br /&gt;&amp;lt;param name="pc" value="&lt;%= @pc.join(" ") %&gt;"&gt;&lt;br /&gt;&amp;lt;hr /&gt;&lt;br /&gt;If you were using a Java-enabled browser,&lt;br /&gt;you would see an applet right now.&lt;br /&gt;&amp;lt;hr /&gt;&lt;br /&gt;&amp;lt;/applet&gt;&lt;/pre&gt;&lt;br /&gt;The code base points to the public/applets folder (using a constant, SITE, for the domain and port). The two variables @rt and @pc are arrays of floats, which are compiled into strings. These can then be picked up by the applet.&lt;br /&gt;&lt;br /&gt;Okay, so I have got the data from the database, and into my applet. The uses plays around with it, then wants to send the results back to the database. There are number of ways to get data out of an applet. One such is to use a JSObject in the applet to communicate with elements on the web page. However, the easiest way is to use JavaScript.&lt;br /&gt;&lt;br /&gt;This JavaScript function will search the page for the "myapplet" element, then call the getOutput() method on it (retrieving the data from the applet). The string is placed in the "output" element.&lt;br /&gt;&lt;pre&gt;&amp;lt;script language="JavaScript"&gt;&lt;br /&gt;function getOutput() {&lt;br /&gt;document.getElementById('output').value = document.getElementById('myapplet').getOutput();&lt;br /&gt;}&lt;br /&gt;&amp;lt;/script&gt;&lt;/pre&gt;&lt;br /&gt;To get it all to work, you need a little form on the web page, with a button and a hidden  input. Click the button and the results will go on the hidden input, and the form then submitted.&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag :action =&gt; :glc_update do %&gt;&lt;br /&gt;  &amp;lt;input type="hidden" name="output" id="output" /&gt;&lt;br /&gt;  &amp;lt;button type="button" onclick="getOutput(); submit();"&gt;Okay&amp;lt;/button&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;After that, it is up to Rails to examine the string, extracting the results.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5099329003230193199?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5099329003230193199/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5099329003230193199' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5099329003230193199'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5099329003230193199'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2010/01/using-java-applets.html' title='Using Java Applets'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4329162509188359854</id><published>2009-12-22T21:45:00.002Z</published><updated>2009-12-22T21:50:26.888Z</updated><title type='text'>The named_scope in Rails</title><content type='html'>The named_scope method allows you to set up shortcuts to narrow searches within set parameters. It is invoked in the model, something like this:&lt;br /&gt;&lt;pre&gt;class Computer &amp;lt; ActiveRecord::Base&lt;br /&gt;named_scope :active, :conditions =&gt; {:in_use =&gt; true}&lt;br /&gt;named_scope :networked, :conditions =&gt; "(network_id &amp;lt;&gt; \"\")"&lt;br /&gt;named_scope :recent,    lambda { {:conditions =&gt; ["created_at &gt; ?", 1.months.ago ] } }&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Note the use of the lambda. If you simply compared the created_at to the date, you would be comparing it to the date the named_scope was invoked, rather than the current date (you might object that Rails reloads the model each time, so the difference might not be so much, but that does not seem to affect your named_scopes). You might also want to do this if you want to access another model. Say your database has a list of types, and this model has a field for the ID of one of those types. You want to collect all the records by the name of the type, so you need to access the table for the other model to get the ID. But that model might not be loaded when this one is, so you have to delay getting the ID. Or perhaps you want to send parameters to a named_scope through the lambda.&lt;br /&gt;&lt;pre&gt;# Use a lambda to access a later loading model&lt;br /&gt;named_scope :blue, lambda {&lt;br /&gt;{ :conditions =&gt; ["(colour_id = #{Colour.find_by_name('blue').id})"] }&lt;br /&gt;}&lt;br /&gt;# Use a lambda to allow parameters&lt;br /&gt;named_scope :located, lambda { |loc|&lt;br /&gt;{ :conditions =&gt; {:location_id =&gt; loc } }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;You can also use named_scopes for other things, such as ordering.&lt;br /&gt;named_scope :ordered, :order =&gt; 'created_at ASC'&lt;br /&gt;Now to get an array of computers in use, just do this:&lt;br /&gt;&lt;pre&gt;Computer.active&lt;/pre&gt;&lt;br /&gt;You can chain named_scopes together, and also with find. Now I can list all the blue computers at location 5, in ascending order of record creation, or all the networked computers running WinXP just like this:&lt;br /&gt;&lt;pre&gt;Computer.blue.located(5).ordered&lt;br /&gt;Computer.networked.find_by_os("winxp")&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;References&lt;/strong&gt;&lt;br /&gt;&lt;a href="http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know"&gt;http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know&lt;/a&gt;&lt;br /&gt;&lt;a href="http://snippets.aktagon.com/snippets/210-How-to-use-named-scope-in-Rails"&gt;http://snippets.aktagon.com/snippets/210-How-to-use-named-scope-in-Rails&lt;/a&gt;&lt;br /&gt;&lt;a href="http://jitu-blog.blogspot.com/2009/07/looking-into-rails-namedscope.html"&gt;http://jitu-blog.blogspot.com/2009/07/looking-into-rails-namedscope.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://stackoverflow.com/questions/137630/encapsulating-sql-in-a-namedscope"&gt;http://stackoverflow.com/questions/137630/encapsulating-sql-in-a-namedscope&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Notes&lt;/strong&gt;&lt;br /&gt;A named_space can be used with will_paginate without a problem:&lt;br /&gt;&lt;pre&gt;@samples = Sample.outstanding.ordered.paginate :page =&gt; params[:page], :per_page =&gt; 16&lt;/pre&gt;&lt;br /&gt;I found that I had to restart my web server when trying these out to get the named_scopes to reload.&lt;br /&gt;&lt;br /&gt;Also, if named_scope does not like your condition, it just fails to define a new method. There is no warning or hint about what could be wrong. All you get is a method_missing complaint when you try to invoke it.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4329162509188359854?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4329162509188359854/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4329162509188359854' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4329162509188359854'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4329162509188359854'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/12/namedscope-in-rails.html' title='The named_scope in Rails'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4949566063946797876</id><published>2009-12-16T21:31:00.004Z</published><updated>2010-05-04T10:48:28.283+01:00</updated><title type='text'>Using Sub-directories in Rails Projects</title><content type='html'>If you have a big project, you are going to want to break it up into parts, grouping, say, controllers for a certain part in one sub-directory. I found a couple of blog pages saying how to do this (basically you set up a name space in routes.rb, and prefix the controller class names with that name space, with the views in a similarly-named subdirectory):&lt;br /&gt;&lt;br /&gt;&lt;a href="http://myles.eftos.id.au/blog/2005/11/15/sub-directories-on-rails/"&gt;http://myles.eftos.id.au/blog/2005/11/15/sub-directories-on-rails/&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.purpleworkshops.com/articles/grouped-controllers"&gt;http://www.purpleworkshops.com/articles/grouped-controllers&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;However, they paint it rather simpler than it really is.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The Namespace for Controllers&lt;/strong&gt;&lt;br /&gt;Okay, so I have a number of controllers relating to a sample logging system, and I want to put them all inside a directory called sample_log. This corresponds to a Ruby namespace (because I might have a controller called TopController in each part of the system, so Rails needs a way to guarantee they are distinct). All the views need to be in their own subdirectory too, with the same name. Each of my controllers' class name needs to be prefixed with the name of the namespace:&lt;br /&gt;&lt;pre&gt;class SampleLog::SamplesController &amp;lt; ApplicationController&lt;/pre&gt;&lt;br /&gt;Then you need to set up your routes, so that Rails knows you are using a namespace:&lt;br /&gt;&lt;pre&gt;map.namespace :sample_log do |submap|&lt;br /&gt;submap.resources :samples&lt;br /&gt;# other controllers&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;At this point, you should be able to get pages, with a URL something like this:&lt;br /&gt;&lt;pre&gt;http://localhost:3000/sample_log/samples/&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Links&lt;/strong&gt;&lt;br /&gt;So far so good. The tricky part (especially if you already have a project that you want to do this to) is handling links in and out of the subdirectory. The standard link_to method invocation looks like this:&lt;br /&gt;&lt;pre&gt;link_to 'Cylinders', :controller =&gt; 'cylinders'&lt;/pre&gt;&lt;br /&gt;This will generate a link &lt;em&gt;within&lt;/em&gt; the sub-directory. How do you link to other subdirectories, or to the top level? Append a slash to your controller name, like this:&lt;br /&gt;&lt;pre&gt;link_to 'Cylinders', :controller =&gt; '/cylinders'&lt;br /&gt;link_to 'Samples', :controller =&gt; '/sample_log/samples'&lt;/pre&gt;&lt;br /&gt;The various helper methods like new_samples_path and edit_samples_path seem to work fine, but require the directory name to be appended to the method name (run &lt;code&gt;rake routes&lt;/code&gt; to see the helper methods listed):&lt;br /&gt;&lt;pre&gt;link_to 'List', sample_log_generic_samples_path&lt;br /&gt;link_to 'Show', sample_log_generic_sample_path(@sample)&lt;br /&gt;link_to 'Edit', edit_sample_log_generic_sample_path(@sample)&lt;br /&gt;redirect_to sample_log_samples_path&lt;/pre&gt;&lt;br /&gt;However, Rails does not seem to be able to cope with links like this (use the helper methods just mentioned instead):&lt;br /&gt;&lt;pre&gt;link_to 'Show', @sample&lt;br /&gt;redirect_to @sample&lt;/pre&gt;&lt;br /&gt;For some reason, Rails does not provide a helper method for destroy, so you will need to given that link through the action:&lt;br /&gt;&lt;pre&gt;link_to 'Destroy', { :action =&gt; :destroy, :id =&gt; sample.id },&lt;br /&gt;               :confirm =&gt; 'Are you sure?',&lt;br /&gt;               :method =&gt; :delete&lt;/pre&gt;&lt;br /&gt;If you use the &lt;code&gt;form_for&lt;/code&gt; functionality, or polymophic methods (presumably with STI), you need to send the directory as a parameter (as a symbol or string), wrapped up in an array:&lt;br /&gt;&lt;pre&gt;form_for([:sample_log, @sample]) do |f|&lt;br /&gt;link_to 'Edit', edit_polymorphic_path([:sample_log, @samples[1]])&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Pointing to templates and partials&lt;/strong&gt;&lt;br /&gt;Any time you explicitly invoke a template in a controller, you will obviously need to change that so it points to the correct directory, and in your views, your partials will need to be adjusted similarly if you are using the full directory path (which you might do if the partial is in the directory of another controller).&lt;br /&gt;&lt;pre&gt;# This works (as does the implicit version, i.e., no render statement at all)&lt;br /&gt;render :action =&gt; 'show'&lt;br /&gt;&lt;br /&gt;# This&lt;br /&gt;render :template =&gt; 'samples/show'&lt;br /&gt;# ...becomes this&lt;br /&gt;render :template =&gt; 'sample_log/samples/show'&lt;br /&gt;&lt;br /&gt;# This&lt;br /&gt;render :partial =&gt; 'samples/list_table_row',&lt;br /&gt;             :collection =&gt; @samples&lt;br /&gt;# ... becomes this&lt;br /&gt;render :partial =&gt; 'sample_log/samples/list_table_row',&lt;br /&gt;             :collection =&gt; @samples&lt;br /&gt;&lt;br /&gt;# But this stays the same&lt;br /&gt;render :partial =&gt; 'list_table_row',&lt;br /&gt;             :collection =&gt; @samples&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Functional Testing&lt;/strong&gt;&lt;br /&gt;You will need to modify your functional tests. Just as with the controllers, they need to go into an identically name directory, and put into the correct name space. Rake will find the tests in subdirectories without any prompting.&lt;br /&gt;&lt;pre&gt;class SampleLog::SamplesControllerTest &amp;lt; ActionController::TestCase&lt;/pre&gt;&lt;br /&gt;Besides that, the other major change is to make sure all your paths are defined using helper methods, as in the controller.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Integration Testing&lt;/strong&gt;&lt;br /&gt;These tests will need to be modified so your HTTP requests point to the right URL, and the templates you expect are in the right folder&lt;br /&gt;&lt;pre&gt;# This&lt;br /&gt;get "/samples/home"&lt;br /&gt;# ... becomes&lt;br /&gt;get "/sample_log/samples/home"&lt;br /&gt;&lt;br /&gt;# This&lt;br /&gt;assert_template "samples/home"&lt;br /&gt;# ... becomes&lt;br /&gt;assert_template "sample_log/samples/home"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Models&lt;/strong&gt;&lt;br /&gt;Controllers and views are closely coupled, so if you want your controllers in a subdirectory, your views must be in an identically named subdirectory. On the other hand, your models can be handled independantly (when I was trying this out, I moved the controllers and views of one section first, and had the project working fine with the corresponding models still in the top app/model directory, then I moved all the models for all the sections, and again had it working fine, then moved the remaining controllers and views). That said, it would seem to me that best practice has to be to have your directory structure identical for controllers, views and models.&lt;br /&gt;&lt;br /&gt;You have two choices with the models. The first is to use the same namespace concept as the controllers. In this case, the database name also needs to have the nampespace prepended.&lt;br /&gt;&lt;pre&gt;sample_log/sample.rb    # The file name&lt;br /&gt;SampleLog::Sample       # The class name&lt;br /&gt;sample_log_samples      # The database&lt;/pre&gt;&lt;br /&gt;That is probably the best way to go if you are starting from scratch, but if you are modifying an existing project, you could find that there are a lot of changes required (and so a lot of potential for errors).&lt;br /&gt;&lt;br /&gt;The alternative is to forget the name spaces, and just make sure Rails can find your files. Two (nearly identical) approaches can be seen here:&lt;br /&gt;&lt;br /&gt;&lt;a href="http://toolmantim.com/articles/keeping_models_in_subdirectories"&gt;http://toolmantim.com/articles/keeping_models_in_subdirectories&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.paperplanes.de/2007/5/2/namespacing_your_rails_model_an.html"&gt;http://www.paperplanes.de/2007/5/2/namespacing_your_rails_model_an.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;The basic idea is that you tell Rails about the location of your models. Rails keeps an array of paths that it loads from, so you need to add your new paths to that in config/environment.rb. This code snippet adds three folders, sample_log, computer_log and user_log and would go inside the &lt;code&gt;Rails::Initializer.run do |config|&lt;/code&gt; block.&lt;br /&gt;&lt;pre&gt;ary = %w(sample computer user)&lt;br /&gt;ary.each do |dir|&lt;br /&gt; config.load_paths &lt;&lt; "#{RAILS_ROOT}/app/models/#{dir}_log" end&lt;/pre&gt;&lt;br /&gt;That is all you need to do for your models. The unit tests can be shifted into their own subdirectory if you want (and I think you should), but none of the unit test or model files need to be changed at all.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;ActionMailer&lt;/span&gt;&lt;br /&gt;One last point. If you put your ActionMailer templates in a subdirectory, you need to tell ActionMailer where to find them. You do that in config/environment.rb, inside the big &lt;code&gt;Rails::Initializer.run&lt;/code&gt; block, like this:&lt;br /&gt;&lt;pre&gt;config.action_mailer.template_root = "#{RAILS_ROOT}/app/views/#{my_sub_dir}"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4949566063946797876?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4949566063946797876/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4949566063946797876' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4949566063946797876'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4949566063946797876'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/12/using-sub-directories-in-rails-projects.html' title='Using Sub-directories in Rails Projects'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-476896854290687904</id><published>2009-11-07T13:17:00.003Z</published><updated>2010-04-14T14:10:25.726+01:00</updated><title type='text'>Ruby Arrays</title><content type='html'>An array is a group of values in a certain order. You can mix-and-match what you put in the array (it is all objects with Ruby), including hashes and other arrays.&lt;br /&gt;&lt;pre&gt;a = ['one', 2, 3.0]&lt;/pre&gt;&lt;br /&gt;A quick way to create an array of strings (if each string is a single word) is like this (you can use any matching brackets, or indeed more punctuation):&lt;br /&gt;&lt;pre&gt;a = %w(one two three)&lt;br /&gt;# =&gt; ["One", "Two", "Three"]&lt;/pre&gt;&lt;br /&gt;To add an element to an existing array do this:&lt;br /&gt;&lt;pre&gt;array &amp;lt;&amp;lt; "new element"&lt;/pre&gt;You can join two arrays using the addition operator.&lt;br /&gt;&lt;pre&gt;b = [4, 16]&lt;br /&gt;c = a + b&lt;br /&gt;# =&gt;  ["One", "Two", "Three", 4, 16]&lt;/pre&gt;&lt;br /&gt;Use &lt;code&gt;include?&lt;/code&gt; to determine if the given object is in the array. To access an array member use &lt;code&gt;[]&lt;/code&gt;, or &lt;code&gt;at&lt;/code&gt; or &lt;code&gt;fetch&lt;/code&gt;. The &lt;code&gt;[]&lt;/code&gt; and &lt;code&gt;at&lt;/code&gt; methods return &lt;code&gt;nil&lt;/code&gt; if the index is out of range, while &lt;code&gt;fetch&lt;/code&gt; throws an exception, or a default value of given. A negative index counts back from the end, while a range returns a subset of the array.&lt;br /&gt;&lt;pre&gt;ary = %w(zero one two three four five six)&lt;br /&gt;p ary[2]&lt;br /&gt;# =&gt; "two"&lt;br /&gt;p ary.at(3)&lt;br /&gt;# =&gt; "three"&lt;br /&gt;p ary[-1]&lt;br /&gt;# =&gt; "six"&lt;br /&gt;p ary[2..4]&lt;br /&gt;# =&gt; ["two, "three", "four"]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;delete_if&lt;/strong&gt;&lt;br /&gt;Ruby has some very neat tricks with arrays. Want to delete all the elements of an array of hashes that have a body that is nil?&lt;br /&gt;&lt;pre&gt;array.delete_if { |x| x.body.nil? }&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;delete_if&lt;/code&gt; removes from the array any elements that evaulate to true in the block. Note that the &lt;code&gt;delete_if&lt;/code&gt; method seems to ignore the convention of naming methods that affect the object itself with an exclamation mark.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;join&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;join&lt;/code&gt; method concatenates each member of an array into a long string. The supplied parameter is used to separate each item. The * operator does the same.&lt;br /&gt;&lt;pre&gt;a = %w(one two three four)&lt;br /&gt;# =&gt; ["one", "two", "three", "four"]&lt;br /&gt;a * ', '&lt;br /&gt;# =&gt; "one, two, three, four"&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;map, select and reject&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;map&lt;/code&gt; method (aka &lt;code&gt;collect&lt;/code&gt;) constructs a new array by processing each element in the array as per the block, while &lt;code&gt;select&lt;/code&gt; returns a new array containing only those elements where the block evaluates to true. The &lt;code&gt;reject&lt;/code&gt; method gives an array for the elements where the block is not true.&lt;br /&gt;&lt;pre&gt;people = [&lt;br /&gt;{:name =&gt; 'Fred', :age =&gt; 19},&lt;br /&gt;{:name =&gt; 'Boris', :age =&gt; 23},&lt;br /&gt;{:name =&gt; 'Mary', :age =&gt; 27},&lt;br /&gt;]&lt;br /&gt;&lt;br /&gt;p people.map {|e| e[:name]}&lt;br /&gt;# =&gt; ["Fred", "Boris", "Mary"]&lt;br /&gt;&lt;br /&gt;p people.select {|e| e[:age] &lt;&gt; [{:name=&gt;"Fred", :age=&gt;19}]&lt;br /&gt;&lt;br /&gt;p people.reject {|e| e[:age] &lt;&gt; [{:name=&gt;"Boris", :age=&gt;23},&lt;br /&gt;                               {:name=&gt;"Mary", :age=&gt;27}]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;sort&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;sort&lt;/code&gt; method will, as the name suggests, sort the array, using the &lt;code&gt;&lt;=&gt;&lt;/code&gt; relationship. Alternatively you can supply block to have it sorted by a custom comparison.&lt;br /&gt;&lt;pre&gt;people.sort { |a, b| a[:age] &lt;=&gt; b[:age] }&lt;br /&gt;   # youngest to oldest&lt;/pre&gt;&lt;br /&gt;Note that your comparison must return -1, 0, or +1. In this example, I therefore could not use &amp;lt;.&lt;br /&gt;&lt;br /&gt;If you use the &lt;code&gt;Enumerable&lt;/code&gt; mixin discussed later you also have a &lt;code&gt;sort_by&lt;/code&gt; method. This is not as fast to run, but can be quicker to code. In this method, the block determines a value for the element, for ranking purposes. Here is the previous example re-written.&lt;br /&gt;&lt;pre&gt;people.sort_by { |a| a[:age] }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;pop and push, shift and unshift&lt;/strong&gt;&lt;br /&gt;You can use &lt;code&gt;push&lt;/code&gt; and &lt;code&gt;pop&lt;/code&gt; to add or remove the last element, and &lt;code&gt;unshift&lt;!--/code--&gt; and &lt;code&gt;shift&lt;/code&gt; to add and remove from the start.&lt;br /&gt;&lt;/code&gt;&lt;pre&gt;a = %w(one two three)&lt;br /&gt;# =&gt; ["one", "two", "three"]&lt;br /&gt;a.push 'four'&lt;br /&gt;# =&gt; ["one", "two", "three", "four"]&lt;br /&gt;a.pop&lt;br /&gt;# =&gt; "four"&lt;br /&gt;a&lt;br /&gt;# =&gt; ["one", "two", "three"]&lt;br /&gt;a.unshift 'zero'&lt;br /&gt;# =&gt; ["zero", "one", "two", "three"]&lt;br /&gt;a.shift&lt;br /&gt;# =&gt; "zero"&lt;br /&gt;a&lt;br /&gt;# =&gt; ["one", "two", "three"]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Extending Array, part 1&lt;/strong&gt;&lt;br /&gt;You can, of course, add your own methods to Array. Here are some examples.&lt;br /&gt;&lt;pre&gt;class Array&lt;br /&gt;&lt;br /&gt;# Shuffle an array&lt;br /&gt;# from http://snippets.dzone.com/posts/show/2994&lt;br /&gt;def shuffle&lt;br /&gt;sort_by { rand }&lt;br /&gt;end&lt;br /&gt;def shuffle!&lt;br /&gt;self.replace shuffle&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# Randomly pick one element of the array.&lt;br /&gt;def pick&lt;br /&gt;fetch rand(length)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# Returns a total over each element in the array&lt;br /&gt;# where the value for an element is determined&lt;br /&gt;# by the given block. This example will look&lt;br /&gt;# through an array of hashes&lt;br /&gt;# and return the total of the square of values&lt;br /&gt;# with the key :value&lt;br /&gt;# ary.total { |e| e[:value] * e[:value] }&lt;br /&gt;def total &amp;amp;prc&lt;br /&gt;val = 0&lt;br /&gt;each do |e|&lt;br /&gt; val += prc.call(e)&lt;br /&gt;end&lt;br /&gt;val&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# Returns an element that best fits the criteria&lt;br /&gt;# given by the block. This example will look&lt;br /&gt;# through an array of hashes and return the element&lt;br /&gt;# with the highest value with the key :value&lt;br /&gt;# ary.find_best { |x, y| x[:value] &amp;lt; y[:value] }&lt;br /&gt;def find_best &amp;amp;prc&lt;br /&gt;best = fetch(0)&lt;br /&gt;each { |e| best = e if yield(best, e) }&lt;br /&gt;best&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# Returns the elements of the given array as&lt;br /&gt;# string with each element listed&lt;br /&gt;# in the form "one, two and three".&lt;br /&gt;def list&lt;br /&gt;join(', ').reverse.sub(' ,', ' dna ').reverse&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Extending Array, part 2&lt;/strong&gt;&lt;br /&gt;Another way to extend Array is to "mixin" the Enumerable module.&lt;br /&gt;&lt;pre&gt;class Array&lt;br /&gt;include Enumerable&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This has several interesting methods (and also some that are already in Array). Use &lt;code&gt;any?&lt;/code&gt; and &lt;code&gt;all?&lt;/code&gt; to determine if at least one element evalauates to true on the block, or all of them do.&lt;br /&gt;&lt;pre&gt;a = %w(one two three)&lt;br /&gt;a.any? {|e| e.length == 5}&lt;br /&gt;# =&gt; true&lt;br /&gt;p a.all? {|e| e.length == 5}&lt;br /&gt;# =&gt; false&lt;/pre&gt;&lt;br /&gt;You can find an element in an array using &lt;code&gt;find&lt;/code&gt; (aka &lt;code&gt;detect&lt;/code&gt;). This method returns the first element for which the block evaulates to true. The method takes an optional parameter, this is returned if no element is found that fits.&lt;br /&gt;&lt;pre&gt;people.find { |e| e[:age] == 23 }&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;inject&lt;/code&gt; method combines each element of the array.&lt;br /&gt;&lt;pre&gt;total_age = people.inject(0) { |memo, e| memo += e[:age] }&lt;br /&gt;# =&gt; 69&lt;/pre&gt;&lt;br /&gt;The supplied parameter is the initial value (in this example, zero). This is technically optional, but going to be necessary in most cases (including this example) for the calculation to work in the first iteration. The memo is the ongoing value, so the increment is added to this.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Ref:&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/Array.html"&gt;http://www.ruby-doc.org/core/classes/Array.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://ruby-doc.org/core/classes/Enumerable.html"&gt;http://ruby-doc.org/core/classes/Enumerable.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-476896854290687904?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/476896854290687904/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=476896854290687904' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/476896854290687904'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/476896854290687904'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/11/ruby-arrays.html' title='Ruby Arrays'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-2945130518918109223</id><published>2009-10-22T21:21:00.002+01:00</published><updated>2009-10-22T21:32:27.281+01:00</updated><title type='text'>Duck-typing</title><content type='html'>Let us say I want to be able to output a variety of objects (say strings, floats and dates) on a web page. With Java I would create a new class with over-loaded methods, like this (warning: my Java is getting rusty, and this is untested):&lt;br /&gt;&lt;pre&gt;class Formatter {&lt;br /&gt;  SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");&lt;br /&gt;&lt;br /&gt;  public static String show(String s) { return s; }&lt;br /&gt;  public static String show(Date d) { return sdf.format(d); }&lt;br /&gt;  public static String show(double x) { return x &amp;lt; 0.05 ? '&amp;lt;0.1' : "" + (Math.round(x * 10) / 10.0); }&lt;br /&gt;  public static String show(Object o) { return o.toString(); }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;To invoke, I would use this:&lt;br /&gt;&lt;pre&gt;Formatter.show(myObject);&lt;/pre&gt;&lt;br /&gt;Java will select the method based on the class I send. Note that there is a method for object to catch anything unexpected.&lt;br /&gt;&lt;br /&gt;In Ruby, I would approach this quite differently. There is no need for a new class, just modify the existing classes. This is not possible in Java; I could extend &lt;code&gt;Date&lt;/code&gt;, but I would have to ensure that every date I sent was of my date class. &lt;code&gt;String&lt;/code&gt; and &lt;code&gt;float&lt;/code&gt; cannot be extended at all.&lt;br /&gt;&lt;pre&gt;class String&lt;br /&gt;  def show&lt;br /&gt;    to_s&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Remember the require 'date.rb'&lt;br /&gt;class DateTime&lt;br /&gt;  DATE_FORMAT = '%d/%b/%y'&lt;br /&gt;&lt;br /&gt;  def show&lt;br /&gt;    strftime(DATE_FORMAT)&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class Float&lt;br /&gt;  def show&lt;br /&gt;    self &amp;lt; 0.05 ? '&amp;lt;0.1' : (self * 10).round / 10.0&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class Object&lt;br /&gt;  def show&lt;br /&gt;    to_s&lt;br /&gt;  end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;That is more verbose, but the result is much neater, much more object-orientated, as now the method can be invoked like this:&lt;br /&gt;&lt;pre&gt;my_object.show&lt;/pre&gt;&lt;br /&gt;I have a library of useful Java methods. It is a collection of static methods that do various operations on arrays and strings. In Ruby, I am building up a library that changes how arrays and string behave. Just occasionally, that is not the best way - again because of duck-typing, as it happens. Say I have a method to format dates consistently. All it does is invoke &lt;code&gt;strftime&lt;/code&gt; with a certain format string. I could define my method as part of the &lt;code&gt;DateTime&lt;/code&gt; class, however I would then be unable to use it with Time objects. In this case, I am better adding the method to the Object class, then DateTime, Date and Time objects would all be able to use it, as they all have &lt;code&gt;strftime&lt;/code&gt; methods (and duck-typing allows this to work).&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-2945130518918109223?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/2945130518918109223/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=2945130518918109223' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2945130518918109223'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2945130518918109223'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/10/duck-typing.html' title='Duck-typing'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5822193091973647708</id><published>2009-10-21T20:18:00.002+01:00</published><updated>2009-10-21T20:23:49.073+01:00</updated><title type='text'>The Case Statement and Relationship Operator</title><content type='html'>Ruby supports a case statement, in which the value of something is matched against a set of options&lt;br /&gt;&lt;pre&gt;case value&lt;br /&gt;when 1, 2, 5&lt;br /&gt;do_this&lt;br /&gt;when 3&lt;br /&gt;do_that&lt;br /&gt;else&lt;br /&gt;do_the_other&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;In this example the first &lt;code&gt;when&lt;/code&gt; will catch three different values. Note that unlike the C family of languages, there is no break statement used. Options cannot fall though to the next one.&lt;br /&gt;&lt;br /&gt;You do not need to give a parameter to the &lt;code&gt;case&lt;/code&gt; statement, as seen here.&lt;br /&gt;&lt;pre&gt;case&lt;br /&gt;when @t == 7&lt;br /&gt;p 't is 7'&lt;br /&gt;when @s == :this&lt;br /&gt;p 's is :this'&lt;br /&gt;else&lt;br /&gt;p 'none of the above'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;In this form, the case is like an &lt;code&gt;if/elsif&lt;/code&gt; chain.&lt;br /&gt;&lt;pre&gt;if @t == 7&lt;br /&gt;p 't is 7'&lt;br /&gt;elsif @s == :this&lt;br /&gt;p 's is :this'&lt;br /&gt;else&lt;br /&gt;p 'none of the above'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;So why use case? Well, case returns a value, so instead we could do this:&lt;br /&gt;&lt;pre&gt;s = case&lt;br /&gt;when @t == 7&lt;br /&gt;'t is 7'&lt;br /&gt;when @s == :this&lt;br /&gt;'s is :this'&lt;br /&gt;else&lt;br /&gt;'none of the above'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The Relationship Operator&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;case&lt;/code&gt; statement uses the relationship operator, &lt;code&gt;===&lt;/code&gt; (aka triple equals or trequals operator) when comparing the value to each when. The relationship operator is really a method, and in &lt;code&gt;Object&lt;/code&gt; the relationship operator is defined to do the same as the equals operator. However, the important point here is that it can be overridden as required. Patterns override it to check for a match, and the &lt;code&gt;Range&lt;/code&gt; class overrides it to check if the value is within the range. That allows you to do things like this:&lt;br /&gt;&lt;pre&gt;mark = 56&lt;br /&gt;&lt;br /&gt;grade = case mark&lt;br /&gt;when 1..25&lt;br /&gt;'Fail'&lt;br /&gt;when 26..50&lt;br /&gt;'C'&lt;br /&gt;when 51..75&lt;br /&gt;'B'&lt;br /&gt;when 76..100&lt;br /&gt;'A'&lt;br /&gt;else&lt;br /&gt;'Out of range!'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Here grade is set to 'B' because &lt;code&gt;(51..75) === 56&lt;/code&gt; evaulates to true. Note that this is calling the &lt;code&gt;===&lt;/code&gt; method on &lt;code&gt;51..75&lt;/code&gt;. Write it the other way around, &lt;code&gt;56 === (51..75)&lt;/code&gt;, and the &lt;code&gt;===&lt;/code&gt; method of &lt;code&gt;56&lt;/code&gt; is invoked, and the expression evaluates to false.&lt;br /&gt;&lt;br /&gt;See more here:&lt;br /&gt;&lt;a href="http://www.pmamediagroup.com/2009/07/dont-call-it-case-equality/"&gt;http://www.pmamediagroup.com/2009/07/dont-call-it-case-equality/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5822193091973647708?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5822193091973647708/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5822193091973647708' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5822193091973647708'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5822193091973647708'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/10/case-statement-and-relationship.html' title='The Case Statement and Relationship Operator'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-6327700645908683115</id><published>2009-09-22T21:19:00.005+01:00</published><updated>2010-04-13T10:48:39.962+01:00</updated><title type='text'>Gotchas for Models</title><content type='html'>I have hit a few issues using Rails, some very frustrating. Here are a selection that relate to the models.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Constructors with Arguments&lt;/strong&gt;&lt;br /&gt;The first is how to handle a constructor that will take a parameter. In Ruby, when you call &lt;code&gt;new&lt;/code&gt; for a class, the object is created, then the &lt;code&gt;initialize&lt;/code&gt; method is invoked. If you want to do that for your model, then you need to invoke the &lt;code&gt;initialize&lt;/code&gt; method in the superclass to ensure everything is set up, and that is done through the &lt;code&gt;super&lt;/code&gt; keyword.&lt;br /&gt;&lt;br /&gt;The problem is that &lt;code&gt;super&lt;/code&gt; takes with it all the parameters that were sent to the method. If your &lt;code&gt;initialize&lt;/code&gt; takes two parameters, both parameters get sent to the &lt;code&gt;initialize&lt;/code&gt; in &lt;code&gt;ActiveRecord::Base&lt;/code&gt;, which throws an exception, because it expects just one; a hash. The solution is to use brackets with super; &lt;code&gt;super()&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;On a kind of related note, see this page about why overriding initialize may not be the best solution, as Rails sometimes creates objects another way.&lt;br /&gt;&lt;a href="http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html"&gt;http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Column Values&lt;/strong&gt;&lt;br /&gt;The second gotcha is accessing column values within the model. When you are not in the model, it is very simple:&lt;br /&gt;&lt;pre&gt;@post.title = 'My new title'&lt;br /&gt;s = @post.body&lt;/pre&gt;&lt;br /&gt;Ruby and Rails work together to make this seem as though you are accessing a variable in a class. However, the reality is that you are invoking methods, and this runs into problems when you do it from inside the class. You might imagine that this would work:&lt;br /&gt;&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base&lt;br /&gt; def initialize params = {}&lt;br /&gt;   body = params[:body]&lt;br /&gt;   s = body&lt;br /&gt;   title = "Post: #{s[0..100]}"&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;It does not. The &lt;code&gt;s = body&lt;/code&gt; line is fine; I guess Ruby notes that no variable called body exists, so invokes the &lt;code&gt;method_missing&lt;/code&gt; method, and everything is good. Not so with &lt;code&gt;title = 'My new title'&lt;/code&gt;. Ruby assumes that this is an assignment to a new variable, rather than a method invocation (why does the interpretor not check in the method exists first? I can only assume this is a performance issue). This has lead to some obscure bugs where values are mysteriously failing to get assigned. The solution is to prefix with &lt;code&gt;self.&lt;/code&gt;, which gives Ruby the hint that this is a method call.&lt;br /&gt;&lt;pre&gt;class Post &amp;lt; ActiveRecord::Base&lt;br /&gt; def test&lt;br /&gt;   self.title = 'My new title'&lt;br /&gt;   s = body&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Migrations&lt;/strong&gt;&lt;br /&gt;One of the most common reason my unit tests do not work is that I have done a migration on the development database, and forgotten the testing database (&lt;code&gt;rake db:test:prepare&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Fixtures and Migrations&lt;/strong&gt;&lt;br /&gt;When you create a model, some default fixtures are also created for testing. If you subsequently modify the migration file, those fixtures might not work, and you will get an error like this when you run your test:&lt;br /&gt;&lt;pre&gt;ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Reverting to Rails 2.2.2&lt;/strong&gt;&lt;br /&gt;Rails 2.3.2 adds a new helper file for new models, in units/test/helpers. If you then revert to 2.2.2, this will crash rake when you run your unit tests (but other tests will be okay).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Saving records&lt;/strong&gt;&lt;br /&gt;When you save a record (and it is not a new record), Rails will work out what has changed, and only update those fields that have actually changed. However, it is not that reliable at spotting a change. In this example, no change is made.&lt;br /&gt;&lt;pre&gt;r = MyRecord.find 19&lt;br /&gt;r.description.sub! 'this', 'that'&lt;br /&gt;r.save&lt;/pre&gt;&lt;br /&gt;The problem is that Rails uses a flag on each attribute, and if you do not set the flag, the attribute is not updated. Assignment automatically sets the flag, so it is easy to over-look. The following will work fine:&lt;br /&gt;&lt;pre&gt;r = MyRecord.find 19&lt;br /&gt;r.description = r.description.sub 'this', 'that'&lt;br /&gt;r.save&lt;/pre&gt;&lt;br /&gt;The alternative is to tell Rails explicitly that the attribute is being changed:&lt;br /&gt;&lt;pre&gt;r = MyRecord.find 19&lt;br /&gt;r.description_will_change&lt;br /&gt;r.description.sub! 'this', 'that'&lt;br /&gt;r.save&lt;/pre&gt;Refs:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html"&gt;http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects"&gt;http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;First may not be first&lt;/strong&gt;&lt;br /&gt;I have database that has been in use for some ten months ago. I wanted to retrieve the very first sample. Should be easy:&lt;br /&gt;&lt;pre&gt;Sample.find(:first)&lt;/pre&gt;&lt;br /&gt;Apparently not. This was retrieving a record from only a couple of weeks ago, with an ID of 1269. And in my development database, when I tested this, it worked fine. To get the right sample, I had to specify what to order by (I have no idea what ordering brings record 1269 to the front).&lt;br /&gt;&lt;pre&gt;Sample.find(:first, :order =&gt; "created_at ASC")&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Erroneous commas in hash assignments&lt;/strong&gt;&lt;br /&gt;This one is not limited to models. If you are assigning values to a hash, an extra comma can wreak havoc! Usually extraneous punction is ignored (extra semi-colons, for example), or throws an error. Not in this case.&lt;br /&gt;&lt;pre&gt;h = {}&lt;br /&gt;h[:name] = 'Fred'&lt;br /&gt;h[:desc] = 'Big'&lt;br /&gt;&lt;br /&gt;p h.inspect&lt;br /&gt;# =&gt; "{:name=&gt;\"Fred\", :desc=&gt;\"Big\"}"&lt;br /&gt;&lt;br /&gt;h[:name] = 'Fred',&lt;br /&gt;h[:desc] = 'Big'&lt;br /&gt;&lt;br /&gt;p h.inspect&lt;br /&gt;# =&gt; "{:name=&gt;[\"Fred\", \"Big\"], :desc=&gt;\"Big\"}"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Changes to a file not always noted&lt;/strong&gt;&lt;br /&gt;While you are developoing your system, chances are you will have your local web server running, and will be looking at how the web site behaves and looks as you make changes. Generally, this is fine. However, some changes that you make are not going to change the web site, for example, changes to files in &lt;code&gt;config&lt;/code&gt;. If you have the console open, and type &lt;code&gt;reload!&lt;/code&gt; you might find that even changes to your model (I think this may be when connected to the production database, so it is going to be very rare, admittedly). You may need to shut down the console or web server, and restart it to get the changes to have an effect.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-6327700645908683115?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/6327700645908683115/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=6327700645908683115' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6327700645908683115'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6327700645908683115'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/09/gotchas-for-models.html' title='Gotchas for Models'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7945361471697854347</id><published>2009-06-16T21:38:00.002+01:00</published><updated>2009-06-16T21:41:35.600+01:00</updated><title type='text'>Displaying Usage Statistics on a Bar Graph</title><content type='html'>My last post was about creating images of line graphs in Rails. Now I am going to have a go at histograms (bar graphs), using HTML to draw the graph, rather than creating an image.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The Data&lt;/strong&gt;&lt;br /&gt;I recently wanted to see how frequently entries were added to a table in my database. Each entry has a &lt;code&gt;created_at&lt;/code&gt; column, so it should be easy to break this down by week or by month. Or so I thought. It was not as easy as I had hoped. There is no simple Rails way to group records within a set time interval. Instead, I had to use some actual SQL. And as my development PC is running MySQL and my server has PostgreSQL, I had to use two different dialects of SQL. It is not pretty, but this is what worked for me. First, I set up a SQL string (I did this in the controller while trying it out, but moved it to config/initializers/constants.rb later; you need to restart the web server after changing constants.rb):&lt;br /&gt;&lt;pre&gt;module Sql&lt;br /&gt;# SQL to get usage stats by week&lt;br /&gt;&lt;br /&gt;# Different SQL for different dialects&lt;br /&gt;# Both will generate the number of days since the year dot&lt;br /&gt;# when the records was created&lt;br /&gt;# MySQL has year and dayofyear functions&lt;br /&gt;MYSQL_YEAR = 'year(created_at)'&lt;br /&gt;MYSQL_DAY = 'dayofyear(created_at)'&lt;br /&gt;# PostgreSQL uses the extract function for both&lt;br /&gt;POSTGRESQL_YEAR = 'extract(year from created_at)'&lt;br /&gt;POSTGRESQL_DAY = 'extract(doy from created_at)'&lt;br /&gt;# Select the correct SQL based on the name of the database adapter&lt;br /&gt;SQL_YEAR = ActiveRecord::Base.configurations[RAILS_ENV]['adapter'].match(/mysql/) ?&lt;br /&gt;             MYSQL_YEAR : POSTGRESQL_YEAR&lt;br /&gt;SQL_DAY = ActiveRecord::Base.configurations[RAILS_ENV]['adapter'].match(/mysql/) ?&lt;br /&gt;             MYSQL_DAY : POSTGRESQL_DAY&lt;br /&gt;&lt;br /&gt;# The rest of the SQL is the same&lt;br /&gt;# The second line calculates the week number for the record&lt;br /&gt;SQL =&lt;br /&gt;&amp;lt;&amp;lt;END&lt;br /&gt;select count(sample_reference) as count,&lt;br /&gt;      floor((#{SQL_YEAR} * 365 + #{SQL_DAY}) / 7) as week,&lt;br /&gt;      #{SQL_YEAR} as year,&lt;br /&gt;      floor(#{SQL_DAY} / 7) as week_no&lt;br /&gt;      from samples&lt;br /&gt;      group by week&lt;br /&gt;      order by week desc&lt;br /&gt;      ;&lt;br /&gt;END&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You do have to careful when invoking SQL directly that you guard against SQL injection attacks. Not a problem in this case as the SQL command is in no way altered by the end-user.&lt;br /&gt;&lt;br /&gt;SQL does have functions for getting the week number, however, funny things happen just before the new year, with records created in week zero, but in the previous year, so I abandoned using these functions. Months would have easier, but I wanted weeks.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The Controller&lt;/strong&gt;&lt;br /&gt;After all that, the method in my controller is fairly simple. Some sites I looked at used &lt;code&gt;establish_connection&lt;/code&gt; before &lt;code&gt;connection&lt;/code&gt;. As I understand it, &lt;code&gt;establish_connection&lt;/code&gt; tells Rails that you want to potentially make a connection to a database, allowing you to create actual connections as oftyen as you like in the future. Rails does that automatically for ActiveRecord, so there is no need in this situation for me to. The &lt;code&gt;map&lt;/code&gt; method adds a new key-value pair to each hash in the array; this will be used for the labels (eg "2009 week 3").&lt;br /&gt;&lt;pre&gt;def graph&lt;br /&gt;ary = ActiveRecord::Base.connection.select_all(Sql::SQL)&lt;br /&gt;@result = ary.map do |e|&lt;br /&gt;  e['label'] = "#{e['year']} week #{e['week_no']}"&lt;br /&gt;  e&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;A Generic Partial&lt;/strong&gt;&lt;br /&gt;I created a partial to display the results in the bar graph. This is a general thing that could be used in any number of web pages to display this sort of data. It uses HTML to extend a small image across a table, according to the data. Note that this uses the &lt;code&gt;find_best&lt;/code&gt; method I described on the &lt;a href="http://strugglingwithruby.blogspot.com/2009/03/ruby-blocks.html"&gt;blocks page&lt;/a&gt;; this pulls out the entry with the highest count, against which all the others are scaled.&lt;br /&gt;&lt;pre&gt;&amp;lt;table&gt;&lt;br /&gt;&amp;lt;%&lt;br /&gt;max = data.find_best { |x, y| x['count'].to_i &amp;lt; y['count'].to_i }['count'].to_i&lt;br /&gt;data.each do |element|&lt;br /&gt;  count = element['count'].to_i&lt;br /&gt;  size = "#{count * 800 / max}x20"&lt;br /&gt;%&gt;&lt;br /&gt;&amp;lt;tr&gt;&lt;br /&gt;  &amp;lt;td&gt;&amp;lt;%=h element['label'] %&gt;&amp;lt;/td&gt;&lt;br /&gt;  &amp;lt;td&gt;&amp;lt;%=h count %&gt;&amp;lt;/td&gt;&lt;br /&gt;  &amp;lt;td&gt;&amp;lt;%= image_tag 'bar.gif', :size =&gt; size %&gt;&amp;lt;/td&gt;&lt;br /&gt;&amp;lt;/tr&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;br /&gt;&amp;lt;/table&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The View&lt;/strong&gt;&lt;br /&gt;The partial is invoked like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= render :partial =&gt; 'bargraph',&lt;br /&gt;              :locals =&gt; { :data =&gt; @result } %&gt;&lt;/pre&gt;&lt;br /&gt;In the &lt;code&gt;locals&lt;/code&gt; hash, &lt;code&gt;:data&lt;/code&gt; is mapped to the array that holds the data. Each entry in the array must have a 'count' value, used for the size of the bar, and another value, the key for which is 'label'.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7945361471697854347?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7945361471697854347/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7945361471697854347' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7945361471697854347'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7945361471697854347'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/06/displaying-usage-statistics-on-bar.html' title='Displaying Usage Statistics on a Bar Graph'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-3465074744977204631</id><published>2009-06-15T21:19:00.002+01:00</published><updated>2009-06-15T21:24:00.660+01:00</updated><title type='text'>Displaying Trends on a Graph Image</title><content type='html'>This builds on my last two posts on drawing images for Rails with Java.&lt;br /&gt;&lt;br /&gt;My objective here was to display values from a series of records on a graph to show possible trends (specifically analytical results for samples submitted to a lab). There are two quite separate issue here involving firstly extracting data from the database table, and secondly creating an image of a line graph on-the-fly.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Getting the Data&lt;/span&gt;&lt;br /&gt;Step one, then, is to grab the data. The easy way is to just use &lt;code&gt;find all&lt;/code&gt;:&lt;br /&gt;&lt;pre&gt;ary = Worksheet.find :all&lt;/pre&gt;&lt;br /&gt;However, that could involve a lot of data coming across from your database that you do not need. We are only interested in the contents of one column. Better to just extract out the data from that column.&lt;br /&gt;&lt;pre&gt;ary = Worksheet.find :all, :select =&gt; 'result'&lt;/pre&gt;&lt;br /&gt;This gives us an array of Worksheet objects, but each object has only the specific column set to a value. We need to grab those values, and the map method gives an easy way to convert to an array of numbers. This can all go inside a class method in Worksheet (in this case the name of the column is in a variable, column_name, to keep it general).&lt;br /&gt;&lt;pre&gt;def self.collect_data column_name&lt;br /&gt;Worksheet.find(:all, :select =&gt; column_name).map do |e|&lt;br /&gt;e.send(column_name)&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Draw the Graph&lt;/span&gt;&lt;br /&gt;Step two is drawing the graph (see also &lt;a href="http://strugglingwithruby.blogspot.com/2009/06/creating-images-for-rails-with-java.html"&gt;here&lt;/a&gt; for drawing with Java on Rails). I created a new Ruby class in its own file in the models directory, using class methods. I wanted the graph to be able to scale itself, but for the lower and upper bounds to be round numbers; the &lt;code&gt;graph_limits&lt;/code&gt; methods handles that.&lt;br /&gt;&lt;br /&gt;Here is the basis of the class. Java needs to be included, and for convenience I have imported all the Java classes I will be using. Then I set up some constants:&lt;br /&gt;&lt;pre&gt;include Java&lt;br /&gt;&lt;br /&gt;class Graph&lt;br /&gt;&lt;br /&gt;java_import java.io.ByteArrayOutputStream&lt;br /&gt;java_import java.awt.image.BufferedImage&lt;br /&gt;java_import java.awt.Color&lt;br /&gt;java_import java.awt.RenderingHints&lt;br /&gt;java_import java.awt.geom.GeneralPath&lt;br /&gt;java_import java.awt.geom.Line2D&lt;br /&gt;java_import java.awt.Font&lt;br /&gt;java_import java.awt.BasicStroke&lt;br /&gt;java_import javax.imageio.ImageIO&lt;br /&gt;&lt;br /&gt;WIDTH = 800&lt;br /&gt;HEIGHT = 600&lt;br /&gt;FOREGROUND = Color.new 0.2, 0.2, 0.2&lt;br /&gt;BACKGROUND = Color.new 0.95, 0.95, 0.95&lt;br /&gt;PLOT = Color.blue&lt;br /&gt;FONT = Font.new("SansSerif", Font::PLAIN, 22)&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I wrote three helper methods (all protected). Note that the second uses the &lt;code&gt;find_best&lt;/code&gt; method I described on the &lt;a href="http://strugglingwithruby.blogspot.com/2009/03/ruby-blocks.html"&gt;blocks page&lt;/a&gt;;&lt;br /&gt;&lt;pre&gt;  # Converts the data point to a vertical&lt;br /&gt;# position on the image,&lt;br /&gt;# scaled between min and max.&lt;br /&gt;def self.calc y, min, max&lt;br /&gt;19.0 * HEIGHT / 20 - (y - min) *&lt;br /&gt;   18 * HEIGHT / (max - min) / 20&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Determines the minimum and maximum&lt;br /&gt;# values from the data, and rounds them&lt;br /&gt;# down and up respectively to give lower&lt;br /&gt;# and upper display limits.&lt;br /&gt;def self.graph_limits data&lt;br /&gt;# See my blocks page for find_best method&lt;br /&gt;min = data.find_best { |x, y| x &gt; y }&lt;br /&gt;max = data.find_best { |x, y| x &amp;lt; y }&lt;br /&gt;modifier = 10 **&lt;br /&gt;        -(Math.log10(max - min).floor)&lt;br /&gt;min = (min * modifier).floor *&lt;br /&gt;        1.0 / modifier&lt;br /&gt;max = (max * modifier).ceil *&lt;br /&gt;        1.0  / modifier&lt;br /&gt;# Ruby allows a method to return&lt;br /&gt;# multiple values&lt;br /&gt;return min, max&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Draws a line and label for the y-axis&lt;br /&gt;def self.graph_line g2, text, h&lt;br /&gt;g2.drawString(text, 0, h)&lt;br /&gt;# Note that Line2D uses inner&lt;br /&gt;#  classes, accessed via ::&lt;br /&gt;g2.draw(Line2D::Double.new(WIDTH / 10,&lt;br /&gt;            h, 9 * WIDTH / 10, h));&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Now that we have the foundations, we can draw the graph.&lt;br /&gt;&lt;pre&gt;  def self.line_graph data&lt;br /&gt;min, max = graph_limits data&lt;br /&gt;&lt;br /&gt;# Set up image object&lt;br /&gt;off_image = BufferedImage.new(WIDTH, HEIGHT,&lt;br /&gt;                 BufferedImage::TYPE_INT_ARGB)&lt;br /&gt;g2 = off_image.createGraphics()&lt;br /&gt;g2.setRenderingHint(RenderingHints::KEY_ANTIALIASING,&lt;br /&gt;        RenderingHints::VALUE_ANTIALIAS_ON)&lt;br /&gt;&lt;br /&gt;# Set up background&lt;br /&gt;g2.setPaint(BACKGROUND)&lt;br /&gt;g2.fillRect(0, 0, WIDTH - 1, HEIGHT - 1)&lt;br /&gt;# Note: You get wierd results if you do not&lt;br /&gt;# fill your background&lt;br /&gt;g2.setPaint(FOREGROUND)&lt;br /&gt;g2.drawRect(0, 0, WIDTH - 1, HEIGHT - 1)&lt;br /&gt;&lt;br /&gt;# Set up the y-axis (no x-axis drawn)&lt;br /&gt;g2.setFont(FONT)&lt;br /&gt;graph_line g2, min.to_s[0..5], HEIGHT * 9 / 10&lt;br /&gt;graph_line g2, max.to_s[0..5], HEIGHT / 10&lt;br /&gt;graph_line g2, ((min + max) / 2).to_s[0..5],&lt;br /&gt;                   HEIGHT / 2&lt;br /&gt;&lt;br /&gt;# Convert data to image coordinates&lt;br /&gt;x_points = Array.new(data.length) do |i|&lt;br /&gt; (i * 8.0 * WIDTH / (data.length - 1) / 10) +&lt;br /&gt;       WIDTH / 10&lt;br /&gt;end&lt;br /&gt;y_points = Array.new(data.length) do |i|&lt;br /&gt;  calc(data[i], min, max)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Generate a GeneralPath object from the&lt;br /&gt;# coordinates&lt;br /&gt;polygon = GeneralPath.new(&lt;br /&gt;               GeneralPath::WIND_EVEN_ODD,&lt;br /&gt;               data.length)&lt;br /&gt;polygon.moveTo(x_points[0], y_points[0])&lt;br /&gt;(1...x_points.length).each do |index|&lt;br /&gt;  polygon.lineTo(x_points[index],&lt;br /&gt;                   y_points[index])&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Draw the GeneralPath object&lt;br /&gt;g2.setPaint(PLOT)&lt;br /&gt;g2.setStroke(BasicStroke.new(1.5))&lt;br /&gt;g2.draw(polygon)&lt;br /&gt;&lt;br /&gt;# Convert for web image&lt;br /&gt;os = java.io.ByteArrayOutputStream.new&lt;br /&gt;ImageIO.write(off_image, "gif", os)&lt;br /&gt;String.from_java_bytes(os.toByteArray)&lt;br /&gt;end&lt;/pre&gt;&lt;span style="font-weight: bold;"&gt;Ptting it Together&lt;/span&gt;&lt;br /&gt;Step 3 is to put it all together. In my controller I put in a new method (this needs to be mentioned as a collection in your routes, as it has no specific record associated with it):&lt;br /&gt;&lt;pre&gt;  def graph&lt;br /&gt;respond_to do |format|&lt;br /&gt;  format.html&lt;br /&gt;  format.gif  do&lt;br /&gt;    send_data Graph.line_graph(&lt;br /&gt;              Worksheet.collect_data('result')),&lt;br /&gt;              :type =&gt; "image/gif",&lt;br /&gt;              :disposition =&gt; "inline"&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The important part is the bit starting with &lt;code&gt;send_data&lt;/code&gt;. The &lt;code&gt;collect_data&lt;/code&gt; method is invoked on Worksheet, returning an array of values from the "result" column of the database table. This is sent to the &lt;code&gt;line_graph&lt;/code&gt; method of Graph, which generates the image.&lt;br /&gt;&lt;br /&gt;Finally, we need a view. This must be called graph.html.erb, of course, and should include the following:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= image_tag "/Worksheet/graph/x.gif", :size =&gt; "800x600" %&gt;&lt;/pre&gt;&lt;br /&gt;If this was an image for a specific record in your table, you would need the id of the record. As this image is for a collection of records, no id is applicable. Nevertheless, you need something there, so I have called in "x".&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-3465074744977204631?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/3465074744977204631/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=3465074744977204631' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3465074744977204631'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3465074744977204631'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/06/displaying-trends-on-graph-image.html' title='Displaying Trends on a Graph Image'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-1541518836572816870</id><published>2009-06-09T20:37:00.003+01:00</published><updated>2009-06-12T08:34:55.592+01:00</updated><title type='text'>Creating Images For Rails With Java</title><content type='html'>Some time ago I had a &lt;a href="http://strugglingwithruby.blogspot.com/2008/08/dynamic-images-on-rails.html"&gt;look at RMagick&lt;/a&gt; to create images on-the-fly in a Rails application. The problem with RMagick is that it is not compatible with JRuby, and if you are going to be using TomCat as your webserver, you need to be using JRuby. However, JRuby does present a ready alternative through Java.&lt;br /&gt;&lt;br /&gt;To look at this I created a new controller, images_controller, in an existing Rails project. In hindsight, images might have been a bad name, as there is a folder called public/images already. However, Rails was able to work out whether the image should come from public/images or via my images controller, so the issue is really only whether it is confusing to the developer.&lt;br /&gt;&lt;br /&gt;The first thing you need to do is set up the new MIME types. There are various places you can do this, but the correct one, I believe, is in config/initializers/mime_types.rb. This is what I added:&lt;br /&gt;&lt;pre&gt;Mime::Type.register "image/jpg", :jpg&lt;br /&gt;Mime::Type.register "image/png", :png&lt;br /&gt;Mime::Type.register "image/gif", :gif&lt;/pre&gt;&lt;br /&gt;Now let us create the controller. The first thing you need to do is include Java. Then you should import all the classes you will need. The second step is optional, but the alternative is writing out the full name of he Java classes every time you use them, which leads to longer and harder to read code. Note that unlike in Java you cannot use the * wildcard to import a whole bunch of classes in one line. Here is the start of my controller:&lt;br /&gt;&lt;pre&gt;class ImagesController &amp;lt; ApplicationController&lt;br /&gt;include Java&lt;br /&gt;&lt;br /&gt;java_import java.io.ByteArrayOutputStream&lt;br /&gt;java_import java.io.File&lt;br /&gt;&lt;br /&gt;java_import java.awt.image.BufferedImage&lt;br /&gt;java_import java.awt.Color&lt;br /&gt;java_import java.awt.RenderingHints&lt;br /&gt;java_import java.awt.geom.GeneralPath&lt;br /&gt;java_import java.awt.Font&lt;br /&gt;&lt;br /&gt;java_import javax.imageio.ImageIO&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Now I need an action defined by a method, &lt;code&gt;image&lt;/code&gt;. A clever feature of Rails is that you can respond differently depending on the file extention, which is what I do here. The &lt;code&gt;respond_to&lt;/code&gt; block directs the action to the correct format (as long as the format is a known MIME type).&lt;br /&gt;&lt;br /&gt;The HTML response is blank. Rails will do the default action, which is to return a page derived from the view &lt;code&gt;images/image.html.erb&lt;/code&gt;. The other three responses follow the same format. Each invokes the &lt;code&gt;send_data&lt;/code&gt; method, with the data (the image) as the first parameter, followed by a hash of options. The &lt;code&gt;:type&lt;/code&gt; is simply the MIME type. The &lt;code&gt;:disposition&lt;/code&gt; determines if the data is to be displayed ("inline"), or downloaded ("attachment"). For attachments, you can set a &lt;code&gt;:filename&lt;/code&gt; parameter too, and there is also a &lt;code&gt;:status&lt;/code&gt; parameter, which conveniently defaults to 200, success.&lt;br /&gt;&lt;br /&gt;API for send_data:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionController/Streaming.html"&gt;http://api.rubyonrails.org/classes/ActionController/Streaming.html&lt;/a&gt;&lt;br /&gt;&lt;pre&gt;def image&lt;br /&gt;@name = params[:id]&lt;br /&gt;&lt;br /&gt;respond_to do |format|&lt;br /&gt; format.html&lt;br /&gt; format.jpg  do&lt;br /&gt;   send_data get_jpeg(@name), :type =&gt; "image/jpeg",&lt;br /&gt;                     :disposition =&gt; "inline"&lt;br /&gt; end&lt;br /&gt; format.png  do&lt;br /&gt;   send_data get_png(@name), :type =&gt; "image/png",&lt;br /&gt;                     :disposition =&gt; "inline"&lt;br /&gt; end&lt;br /&gt; format.gif  do&lt;br /&gt;   send_data get_gif(@name), :type =&gt; "image/gif",&lt;br /&gt;                     :disposition =&gt; "inline"&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;So that just leaves the methods that generate the image data. These should all be protected, by the way.&lt;br /&gt;&lt;br /&gt;This first method simply grabs a file from &lt;code&gt;public/images&lt;/code&gt; and displays it. Once it has the file, it creates an output stream, and writes the image file to that stream in the specified format. It then converts from the stream to a Ruby string, via a Java byte array.&lt;br /&gt;&lt;pre&gt;def get_jpeg filename&lt;br /&gt;imagefile = File.new("#{RAILS_ROOT}/public/images/#{filename}.jpg")&lt;br /&gt;os = ByteArrayOutputStream.new&lt;br /&gt;ImageIO.write(ImageIO.read(imagefile), "jpeg", os)&lt;br /&gt;String.from_java_bytes(os.toByteArray)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Converting to another format is trivial (though noticeably slower).&lt;br /&gt;&lt;pre&gt;def get_png filename&lt;br /&gt;imagefile = File.new("#{RAILS_ROOT}/public/images/#{filename}.jpg")&lt;br /&gt;os = ByteArrayOutputStream.new&lt;br /&gt;ImageIO.write(ImageIO.read(imagefile), "png", os)&lt;br /&gt;String.from_java_bytes(os.toByteArray)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This version does an operation, converting the image to its negative.&lt;br /&gt;&lt;pre&gt;def get_jpeg filename&lt;br /&gt;imagefile = File.new("#{RAILS_ROOT}/public/images/#{filename}.jpg")&lt;br /&gt;bi = ImageIO.read(imagefile)&lt;br /&gt;big = bi.getGraphics&lt;br /&gt;&lt;br /&gt;# Create a look-up table as an array&lt;br /&gt;lut = Array.new(256) { |j| 256 - j }&lt;br /&gt;# Convert to Java byte array&lt;br /&gt;jlut = lut.to_java :byte&lt;br /&gt;# Convert to Java byte look-up table&lt;br /&gt;blut = java.awt.image.ByteLookupTable.new(0, jlut)&lt;br /&gt;# Convert to Java operation look-up table&lt;br /&gt;op = java.awt.image.LookupOp.new(blut, nil)&lt;br /&gt;# Apply the operation&lt;br /&gt;dest = op.filter(bi, nil)&lt;br /&gt;# Draw the new image&lt;br /&gt;big.drawImage(dest, 0, 0, nil);&lt;br /&gt;# Create an output stream, and write the image to it&lt;br /&gt;os = ByteArrayOutputStream.new&lt;br /&gt;ImageIO.write(dest, "jpeg", os)&lt;br /&gt;String.from_java_bytes(os.toByteArray)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The next method actually generates a GIF image on-the-fly, putting the filename in the middle of a simple image. The basic methodology is to create a blank &lt;code&gt;BufferedImage&lt;/code&gt; object (rather than from a file), use that to create a &lt;code&gt;Graphics2d&lt;/code&gt; object (just as before). The image is built by calling methods on the &lt;code&gt;Graphics2d&lt;/code&gt; object, and finally the last three lines create the output stream and write the image to it (just as before).&lt;br /&gt;&lt;pre&gt;WIDTH = 400&lt;br /&gt;HEIGHT = 300&lt;br /&gt;&lt;br /&gt;def get_gif filename&lt;br /&gt;off_image = BufferedImage.new(WIDTH, HEIGHT,&lt;br /&gt;         BufferedImage::TYPE_INT_ARGB)&lt;br /&gt;&lt;br /&gt;g2 = off_image.createGraphics()&lt;br /&gt;g2.setRenderingHint(RenderingHints::KEY_ANTIALIASING,&lt;br /&gt;         RenderingHints::VALUE_ANTIALIAS_ON)&lt;br /&gt;&lt;br /&gt;# Set up background&lt;br /&gt;g2.setPaint(Color.lightGray)&lt;br /&gt;g2.draw3DRect(0, 0, WIDTH - 1, HEIGHT - 1, true);&lt;br /&gt;g2.draw3DRect(3, 3, WIDTH - 7, HEIGHT - 7, false);&lt;br /&gt;&lt;br /&gt;x = 7;&lt;br /&gt;y = 7;&lt;br /&gt;x3_points = [x, WIDTH - 2 * x, x, WIDTH - 2 * x]&lt;br /&gt;y3_points = [y, HEIGHT - 2 * y, HEIGHT - 2 * y, y]&lt;br /&gt;filled_polygon = GeneralPath.new(GeneralPath::WIND_EVEN_ODD,&lt;br /&gt;              x3_points.length);&lt;br /&gt;filled_polygon.moveTo(x3_points[0], y3_points[0])&lt;br /&gt;(1...x3_points.length).each do |index|&lt;br /&gt; filled_polygon.lineTo(x3_points[index], y3_points[index])&lt;br /&gt;end&lt;br /&gt;filled_polygon.closePath()&lt;br /&gt;g2.setPaint(Color.red)&lt;br /&gt;g2.fill(filled_polygon)&lt;br /&gt;g2.setPaint(Color.black)&lt;br /&gt;g2.draw(filled_polygon)&lt;br /&gt;g2.setPaint(Color.yellow)&lt;br /&gt;g2.setFont(Font.new("Helvetica", Font::PLAIN, 22))&lt;br /&gt;g2.drawString(filename, WIDTH / 2, HEIGHT / 2)&lt;br /&gt;&lt;br /&gt;os = java.io.ByteArrayOutputStream.new&lt;br /&gt;ImageIO.write(off_image, "gif", os)&lt;br /&gt;String.from_java_bytes(os.toByteArray)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Okay, so we can generate images; how do we get them on to a web browser? The easy way (to test the above work) is to invoke it though the address bar. Say I have an image saved in public/images called sheep.jpg, I can use the following:&lt;br /&gt;&lt;pre&gt;http://localhost:3000/images/image/sheep.jpg&lt;br /&gt;# =&gt; Gives a negative of the image&lt;br /&gt;http://localhost:3000/images/image/sheep.png&lt;br /&gt;# =&gt; Gives the PNG converted image&lt;br /&gt;http://localhost:3000/images/image/sheep.gif&lt;br /&gt;# =&gt; Gives the generated GIF with "sheep" written on it&lt;/pre&gt;&lt;br /&gt;What we really want to to have those images embedded in a web page. So here is a view, &lt;code&gt;views/images/image.html.erb&lt;/code&gt;, that will do just that:&lt;br /&gt;&lt;pre&gt;&amp;lt;h1&gt;My &amp;lt;%= @name %&gt; image&amp;lt;/h1&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image has been generated on the fly and served via my controller %&gt;&lt;br /&gt;&amp;lt;%= image_tag "/images/image/#{@name}.gif", :size =&gt; '400x300' %&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image has been processed and served via my controller %&gt;&lt;br /&gt;&amp;lt;%= image_tag "/images/image/#{@name}.jpg", :size =&gt; '400x300' %&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image has been processed and served via my controller; uses HTML tags directly %&gt;&lt;br /&gt;&amp;lt;img alt="Sheep" height="300" src="/images/image/&amp;lt;%= @name %&gt;.jpg" width="400" /&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image has been processed and served via my controller as a PNG %&gt;&lt;br /&gt;&amp;lt;%= image_tag "/images/image/#{@name}.png", :size =&gt; '400x300' %&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image came directly from public/images %&gt;&lt;br /&gt;&amp;lt;%= image_tag "/images/#{@name}.jpg", :size =&gt; '400x300' %&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%# This image has been processed and served via my controller, va a helper method %&gt;&lt;br /&gt;&amp;lt;%= images_image_tag @name, :jpg, :size =&gt; '400x300' %&gt;&lt;/pre&gt;&lt;br /&gt;One of those methods uses a helper method, and that would be my prefered way. Here is that method:&lt;br /&gt;&lt;pre&gt;def images_image_tag name, type, options = {}&lt;br /&gt;image_tag "/images/image/#{@name}.#{type.to_s}", options&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-1541518836572816870?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/1541518836572816870/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=1541518836572816870' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1541518836572816870'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1541518836572816870'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/06/creating-images-for-rails-with-java.html' title='Creating Images For Rails With Java'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4491697392506327576</id><published>2009-06-08T21:20:00.006+01:00</published><updated>2009-06-12T08:34:16.698+01:00</updated><title type='text'>JRuby and Java</title><content type='html'>If you are using JRuby you can access Java functionality in your Ruby code pretty easily. Two possible reasons to do this are to create an involved user interface (for simple GUIs the Shoes toolkit is excellent, but it is somewhat limited), and to create images on-the-fly for your Rails application (RMagick offers an alternative, but cannot be used with Tomcat, which requires JRuby). I may  be posting on both these later, but first, I want to explore the basics of using Java from Ruby.&lt;br /&gt;&lt;br /&gt;I am using NetBeans, which has a particular file structure for projects, and also makes the creation of a JAR file very easy (just press F11 and the main project gets built and compressed into a JAR file inside the dist folder). For testing purposes, I created a project called JavaForRuby (and so a package name javaforruby), with a simple test class, &lt;code&gt;TestObject&lt;/code&gt;, which has two instance variables, with setters and getters, and a static method, &lt;code&gt;getStatus&lt;/code&gt;, which returns a &lt;code&gt;String&lt;/code&gt; object.&lt;br /&gt;&lt;br /&gt;And so to the Ruby side. You need to be running JRuby, of course. I had some problems getting my Java classes to work, and this seemed to be resolved by using a more recent version of JRuby (1.3.0RC1), though I am sure it should work with older versions.&lt;br /&gt;&lt;br /&gt;The first thing to do is introduce Java to Ruby, then you need to get your JAR linked up, and then your class loaded. Once that is done, the class can be accessed:&lt;br /&gt;&lt;pre&gt;include Java&lt;br /&gt;&lt;br /&gt;require "#{File.dirname(__FILE__)}/../../JavaForRuby/dist/javaforruby.jar"&lt;br /&gt;&lt;br /&gt;include_class "javaforruby.TestObject"&lt;br /&gt;&lt;br /&gt;p TestObject.getStatus&lt;/pre&gt;&lt;br /&gt;Creating and using an instance of a Java object is simple:&lt;br /&gt;&lt;pre&gt;tobj = TestObject.new 'My Tester', 5&lt;br /&gt;p tobj.class      # =&gt; Java::Javaforruby::TestObject&lt;br /&gt;p tobj.java_class # =&gt; class javaforruby.TestObject&lt;br /&gt;p tobj.get_name   # =&gt; "class javaforruby.TestObject"My Tester"&lt;br /&gt;p tobj.get_value  # =&gt; 5&lt;br /&gt;tobj.set_name 'My Renamed Tester'&lt;br /&gt;p tobj.get_name   # =&gt; "My Renamed Tester"&lt;/pre&gt;&lt;br /&gt;Note that I used the conventions of Java to define the object, but the conventions of Ruby to access it from Ruby; JRuby has associated &lt;code&gt;get_name&lt;/code&gt; in Ruby with &lt;code&gt;getName()&lt;/code&gt; in Java.&lt;br /&gt;&lt;br /&gt;Let us try using an array. JRuby adds a &lt;code&gt;to_java&lt;/code&gt; method to &lt;code&gt;Array&lt;/code&gt;, and this takes a single parameter, the class of the objects for the array.&lt;br /&gt;&lt;pre&gt;ja = %w(one two three).to_java :string&lt;br /&gt;p ja.java_class     # =&gt; [Ljava.lang.String;&lt;br /&gt;p ja[0]             # =&gt; "one"&lt;br /&gt;p ja[0].class       # =&gt; String&lt;br /&gt;ja.each { |e| p e } # =&gt; "one"&lt;br /&gt;                   "two"&lt;br /&gt;                   "three"&lt;/pre&gt;&lt;br /&gt;What happens if you do not tell it the object type? Well, the &lt;code&gt;each&lt;/code&gt; method still works the same; the system works out what each object is. Accessing elements by their index is not so good (I did wonder if fetch might work, but throws an &lt;code&gt;NoMethodError&lt;/code&gt; exception).&lt;br /&gt;&lt;pre&gt;ja = %w(one two three).to_java&lt;br /&gt;p ja.java_class     # =&gt; [Ljava.lang.Object;&lt;br /&gt;p ja[0]             # =&gt; #&amp;lt;Java::JavaLang::String:0x155d3a3 @java_object=#&amp;lt;Java::JavaObject:0x57e787&gt;&gt;&lt;br /&gt;p ja[0].class       # =&gt; "Java::JavaLang::String&lt;br /&gt;ja.each { |e| p e } # =&gt; "one"&lt;br /&gt;                   "two"&lt;br /&gt;                   "three"&lt;/pre&gt;&lt;br /&gt;We can combine the array and the custom class to make a Java array of Java objects in Ruby.&lt;br /&gt;&lt;pre&gt;toja = [&lt;br /&gt;TestObject.new('My First Tester', 5),&lt;br /&gt;TestObject.new('Second', 93),&lt;br /&gt;TestObject.new('Last Tester', 42),&lt;br /&gt;].to_java&lt;br /&gt;&lt;br /&gt;toja.each { |e| p e.get_name }&lt;/pre&gt;&lt;br /&gt;Hashes are no problem either.&lt;br /&gt;&lt;pre&gt;hash = {:name =&gt; 'Fred', :age =&gt; 27}&lt;br /&gt;java_hash = java.util.HashMap.new(hash)&lt;br /&gt;p java_hash.get :name  # =&gt; "Fred"&lt;/pre&gt;&lt;br /&gt;Rather than using the full path name in the method call, you can import each class. You should be able to import a complete package, though I could not get it to work with JRuby 1.3.0RC1 (but I could with 1.1.6).&lt;br /&gt;&lt;pre&gt;java_import "java.util.HashMap"&lt;br /&gt;# import "java.util"&lt;br /&gt;# include_package "java.util"&lt;br /&gt;&lt;br /&gt;hash = {:name =&gt; 'Fred', :age =&gt; 27}&lt;br /&gt;java_hash = HashMap.new(hash)&lt;br /&gt;p java_hash.get :name&lt;/pre&gt;&lt;br /&gt;You can use &lt;code&gt;import&lt;/code&gt; rather than &lt;code&gt;java_import&lt;/code&gt;, and many tutorials indeed do this. However, import  conflicts with Rake, and so, although your system will work as expected, your tests will fail with a NameError and complaints about a 'const_missing' (thanks to Charles Oliver for &lt;a href="http://www.nabble.com/Unit-tests-fail-because-imported-Java-class-names-are-not-recognised.-tt23977787.html#a23977787"&gt;pointing this out&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;Also, I had a problem with &lt;code&gt;import java.io.File&lt;/code&gt;. Ruby warns that the constant &lt;code&gt;File&lt;/code&gt; already exists ("warning: already initialized constant File"), and I think that this gets overwritten, and the code that is expecting the original value gets very confused... You need to restart your web server after that. Again, &lt;code&gt;java_import&lt;/code&gt; seems to fix this.&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://wiki.jruby.org/wiki/Calling_Java_from_JRuby"&gt;http://wiki.jruby.org/wiki/Calling_Java_from_JRuby&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4491697392506327576?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4491697392506327576/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4491697392506327576' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4491697392506327576'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4491697392506327576'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/06/jruby-and-java.html' title='JRuby and Java'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4201308579309139795</id><published>2009-05-12T21:58:00.002+01:00</published><updated>2009-05-12T22:16:23.855+01:00</updated><title type='text'>Date and Time in Rails</title><content type='html'>Rails adds some extra time and date functionality to Ruby, and so you can do cool things like &lt;code&gt;10.years&lt;/code&gt;. However, when you scratch below the surface, it all becomes a bit mysterious. I put this into a view to investigate:&lt;br /&gt;&lt;pre&gt;&amp;lt;%&lt;br /&gt;[1.seconds, 1.minutes, 1.hours, 1.days, 1.months, 1.years].each do |period|&lt;br /&gt;%&gt;&lt;br /&gt;&amp;lt;ul&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="value=#{period}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="inspect=#{period.inspect}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="class=#{period.class}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="Duration?=#{period.is_a?(ActiveSupport::Duration)}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="to_i=#{period.to_i}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="to_i.class=#{period.to_i.class}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;li&gt;&amp;lt;%="to_i.inspect=#{period.to_i.inspect}"%&gt;&amp;lt;/li&gt;&lt;br /&gt;&amp;lt;/ul&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;The output for seconds looked like this:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;value=1&lt;/li&gt;&lt;br /&gt;&lt;li&gt;inspect=1 second&lt;/li&gt;&lt;br /&gt;&lt;li&gt;class=Fixnum&lt;/li&gt;&lt;br /&gt;&lt;li&gt;Duration?=true&lt;/li&gt;&lt;br /&gt;&lt;li&gt;to_i=1&lt;/li&gt;&lt;br /&gt;&lt;li&gt;to_i.class=Fixnum&lt;/li&gt;&lt;br /&gt;&lt;li&gt;to_i.inspect=1&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;It would seem that what we are using here are &lt;code&gt;ActiveSupport::Duration&lt;/code&gt; objects, which are &lt;i&gt;pretending&lt;/i&gt; to be &lt;code&gt;Fixnum&lt;/code&gt; objects. Their value is the duration in seconds, but an &lt;code&gt;inspect&lt;/code&gt; will add the units, and for days, months and years will give the value in those units (but minutes and hours are given in seconds). I would guess the point here is to fool other methods into treating these objects as &lt;code&gt;Fixnum&lt;/code&gt; objects, while retaining the added functionality. Curiously, the &lt;code&gt;years&lt;/code&gt; method returns an object that pretends to be a &lt;code&gt;Float&lt;/code&gt;, even though it does admit to being an &lt;code&gt;ActiveSupport::Duration&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;By the way, each of these methods has a singular alias; &lt;code&gt;year&lt;/code&gt; can be used instead of &lt;code&gt;years&lt;/code&gt;, etc.&lt;br /&gt;&lt;br /&gt;Something else a little odd here (I am multiply the first by 1.0 to convert to float arithmetic):&lt;br /&gt;&lt;pre&gt;&amp;lt;p&gt;Number of days in a month: &amp;lt;%= 1.0 * 1.months / 1.days %&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;Number of months in a year: &amp;lt;%= 1.years / 1.months %&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;Number of days in a year: &amp;lt;%= 1.years / 1.days %&gt;&amp;lt;/p&gt;&lt;/pre&gt;&lt;br /&gt;The result:&lt;br /&gt;&lt;pre&gt;Number of days in a month: 30.0&lt;br /&gt;Number of months in a year: 12.175&lt;br /&gt;Number of days in a year: 365.25&lt;/pre&gt;&lt;br /&gt;So the Rails system quietly ignores anomolous leap years (the last was in 1900, the next in 2100 so is a reasonable approximation), but more bizarrely has slightly more than 12 months in a year. Would it not have made more sense to have 30.4375 days in a month?&lt;br /&gt;&lt;br /&gt;Rails also introduces the ActiveSupport::TimeWithZone object. This is an object that "acts like" a Time object, but can handle different time zones.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;created_at&lt;/code&gt; and &lt;code&gt;updated_at&lt;/code&gt; fields of an &lt;code&gt;ActiveRecord&lt;/code&gt; return objects of this type. You can also convert an &lt;code&gt;ActiveSupport::Duration&lt;/code&gt; to an &lt;code&gt;ActiveSupport::TimeWithZone&lt;/code&gt;  using &lt;code&gt;ago&lt;/code&gt; (and its alias &lt;code&gt;since&lt;/code&gt;) and &lt;code&gt;from_now&lt;/code&gt; (and its alias &lt;code&gt;until&lt;/code&gt;). Both these statements produce ActiveSupport::TimeWithZone objects:&lt;br /&gt;&lt;pre&gt;first_sample = Sample.find(:first).created_at&lt;br /&gt;now = 0.seconds.ago&lt;/pre&gt;&lt;br /&gt;Arithmetic with ActiveSupport::TimeWithZone objects will give a &lt;code&gt;Float&lt;/code&gt; object representing a number of seconds (surely an &lt;code&gt;ActiveSupport::Duration&lt;/code&gt; masquerading as a &lt;code&gt;Float&lt;/code&gt; would make more sense).&lt;br /&gt;&lt;pre&gt;elapsed = now - first_sample&lt;/pre&gt;&lt;br /&gt;You can use &lt;code&gt;ActiveSupport::TimeWithZone&lt;/code&gt; objects in your database searches.&lt;br /&gt;&lt;pre&gt;# Find all samples changed in the last week&lt;br /&gt;Sample.find :all :conditions =&gt; ["updated_at &gt; ?", 1.week.ago]&lt;br /&gt;# Count all samples created between 1 and 2 years ago.&lt;br /&gt;Sample.count :conditions =&gt; ["created_at &gt; ? AND created_at &lt; ?", 2.years.ago, 1.year.ago]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html"&gt;http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4201308579309139795?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4201308579309139795/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4201308579309139795' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4201308579309139795'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4201308579309139795'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/05/date-and-time-in-rails-rails-adds-some.html' title='Date and Time in Rails'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4900065528322587472</id><published>2009-05-09T23:14:00.005+01:00</published><updated>2010-05-26T13:14:47.680+01:00</updated><title type='text'>Regular Expressions in ruby</title><content type='html'>A &lt;code&gt;Regexp&lt;/code&gt; is a Ruby object representing a RegEx or "regular expression". So what exactly is a "regular expression"? It is a sort of string that can be used to match against another string. You could think of it as a template or a set of rules that a string can be compared to. Creating a Regexp object is much like creating a string, except that you use the forward slash to delimit it, rather than quote marks.&lt;br /&gt;&lt;pre&gt;r = /my regular expression/&lt;/pre&gt;&lt;br /&gt;Alternatively, you can use this notation (you seem to be able to use any punctuation, just like %q for a string and %w for a word array):&lt;br /&gt;&lt;pre&gt;r = %r|my regular expression|&lt;br /&gt;r = %r&lt;my regular="" expression=""&gt;&lt;br /&gt;r = %r=my regular expression=&lt;/my&gt;&lt;/pre&gt;&lt;br /&gt;That regular expression will just match the string "my regular expression", anywhere in a string. The power of regular expressions lies in their use of wild cards, as we will see later.&lt;br /&gt;&lt;br /&gt;Several standard Ruby methods take Regexp objects, but the most basic use is a simple comparison. There are two ways to do that; using the =~ operator or the &lt;code&gt;match&lt;/code&gt; method in &lt;code&gt;String&lt;/code&gt;. Both can be used either way around:&lt;br /&gt;&lt;pre&gt;s = 'Here is my string'&lt;br /&gt;r = /s my/&lt;br /&gt;s.match r&lt;br /&gt;r.match s&lt;br /&gt;s =~ r&lt;br /&gt;r =~ s&lt;/pre&gt;&lt;br /&gt;The difference is that the &lt;code&gt;match&lt;/code&gt; method returns a &lt;code&gt;MatchData&lt;/code&gt; object if a match is found, while the =~ operator gives the position of the match. However, the special variable &lt;code&gt;$~&lt;/code&gt; holds the &lt;code&gt;MatchData&lt;/code&gt; for the last Regexp comparison performed, so this information is still available (personally, I do not like the built-in globals; if you want the &lt;code&gt;MatchData&lt;/code&gt; object, use the &lt;code&gt;match&lt;/code&gt; method, and everyone else with have a better idea of what you are doing). See later for more on &lt;code&gt;MatchData&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;So what can we put into a regular expression? There is a variety of options allowing you to specify your template as broadly or as narrowly as you want.&lt;br /&gt;&lt;pre&gt;.             any character except newline&lt;br /&gt;[ ]           any single character of set&lt;br /&gt;[^ ]          any single character NOT of set&lt;br /&gt;*             0 or more previous regular expression&lt;br /&gt;*?            0 or more previous regular expression (non-greedy)&lt;br /&gt;+             1 or more previous regular expression&lt;br /&gt;+?            1 or more previous regular expression (non-greedy)&lt;br /&gt;?             0 or 1 previous regular expression&lt;br /&gt;??&lt;br /&gt;|             alternation&lt;br /&gt;( )           grouping regular expressions&lt;br /&gt;^             beginning of a line or string&lt;br /&gt;$             end of a line or string&lt;br /&gt;{m,n}        at least m but most n previous regular expression&lt;br /&gt;{m,n}?       at least m but most n previous regular expression (non-greedy)&lt;br /&gt;\1-9          nth previous captured group&lt;br /&gt;\A            beginning of a string&lt;br /&gt;\b            backspace(0x08)(inside[]only)&lt;br /&gt;\b            word boundary(outside[]only)&lt;br /&gt;\B            non-word boundary&lt;br /&gt;\d            digit, same as[0-9]&lt;br /&gt;\D            non-digit&lt;br /&gt;\S            non-whitespace character&lt;br /&gt;\s            whitespace character[ \t\n\r\f]&lt;br /&gt;\W            non-word character&lt;br /&gt;\w            word character[0-9A-Za-z_]&lt;br /&gt;\z            end of a string&lt;br /&gt;\Z            end of a string, or before newline at the end&lt;br /&gt;\/            forward slash&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Some simple examples&lt;/strong&gt;&lt;br /&gt;Here are some examples to get us going.&lt;br /&gt;&lt;pre&gt;# Simple pattern matches to dog&lt;br /&gt;p1 = /dog/&lt;br /&gt;p (p1 =~ 'cat-dog') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-doggy') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-dig') # =&gt; nil&lt;br /&gt;p (p1 =~ 'cat-fox') # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Pattern matches to d, any letter, then g&lt;br /&gt;p1 = /d\wg/&lt;br /&gt;p (p1 =~ 'cat-dog') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-doggy') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-dig') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-fox') # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Pattern matches to d, any vowel, then g&lt;br /&gt;p1 = /d[aeiou]g/&lt;br /&gt;p (p1 =~ 'cat-dog') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-doggy') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-dig') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-fox') # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Pattern matches to dog at end of string&lt;br /&gt;p1 = /dog\Z/&lt;br /&gt;p (p1 =~ 'cat-dog') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-doggy') # =&gt; nil&lt;br /&gt;p (p1 =~ 'cat-dig') # =&gt; nil&lt;br /&gt;p (p1 =~ 'cat-fox') # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Pattern matches to d, anything other than o or u, then g&lt;br /&gt;p1 = /d[^ou]g/&lt;br /&gt;p (p1 =~ 'cat-dog') # =&gt; nil&lt;br /&gt;p (p1 =~ 'cat-doggy') # =&gt; nil&lt;br /&gt;p (p1 =~ 'cat-dig') # =&gt; 4&lt;br /&gt;p (p1 =~ 'cat-fox') # =&gt; nil&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The MatchData object&lt;/strong&gt;&lt;br /&gt;If you bracket sections of your Regexp, you can then "capture" these subsections. Each subsection can be accessed as though the &lt;code&gt;MatchData&lt;/code&gt; object as an array, with the first element being the entire matched string (though methods like &lt;code&gt;each&lt;/code&gt; cannot be used). Use the offset method to determine the position in the string for each group. Here it is in action:&lt;br /&gt;&lt;pre&gt;s = "Here is a string with http://www.mydomain.com/path/to/mypage.html in it"&lt;br /&gt;r = /http:\/\/([a-z.]*)(\/[a-z]*)*(\/[a-z]*.html)/i&lt;br /&gt;m = r.match s&lt;br /&gt;p m.string&lt;br /&gt;p m.pre_match&lt;br /&gt;# =&gt; "Here is a string with "&lt;br /&gt;p m.post_match&lt;br /&gt;# =&gt; " in it"&lt;br /&gt;p m[0]&lt;br /&gt;# =&gt; "http://www.mydomain.com/path/to/mypage.html"&lt;br /&gt;p m.offset(0)&lt;br /&gt;# =&gt; [22, 65]&lt;br /&gt;p m[1]&lt;br /&gt;# =&gt; "www.mydomain.com"&lt;br /&gt;p m.offset(1)&lt;br /&gt;# =&gt; [29, 45]&lt;br /&gt;p m[2]&lt;br /&gt;# =&gt; "/to"&lt;br /&gt;p m.offset(2)&lt;br /&gt;# =&gt; [50, 53]&lt;br /&gt;p m[3]&lt;br /&gt;# =&gt; "/mypage.html"&lt;br /&gt;p m.offset(3)&lt;br /&gt;# =&gt; [53, 65]&lt;br /&gt;p m[4]&lt;br /&gt;# =&gt; nil&lt;br /&gt;#p m.offset(4)&lt;br /&gt;# =&gt; IndexError&lt;br /&gt;p m.length&lt;br /&gt;# =&gt; 4&lt;br /&gt;p m.size&lt;br /&gt;# =&gt; 4&lt;/pre&gt;&lt;br /&gt;If you want an actual array, use &lt;code&gt;to_a&lt;/code&gt; or &lt;code&gt;captures&lt;/code&gt; (the latter includes only the capture groups, the former also has the entire match as the first element).&lt;br /&gt;&lt;pre&gt;m.captures.each { |e| p e }&lt;br /&gt;# =&gt; "www.mydomain.com"&lt;br /&gt;# =&gt; "/to"&lt;br /&gt;# =&gt; "/mypage.html"&lt;br /&gt;m.to_a.each { |e| p e }&lt;br /&gt;# =&gt; "http://www.mydomain.com/path/to/mypage.html"&lt;br /&gt;# =&gt; "www.mydomain.com"&lt;br /&gt;# =&gt; "/to"&lt;br /&gt;# =&gt; "/mypage.html"&lt;/pre&gt;&lt;br /&gt;I was surprised to find that you can only capture as many subsections as you have brackets. Even though the Regexp matches one subsection to two parts of the URL ("/path" and "/to"), only the last one appears in the array.&lt;br /&gt;&lt;br /&gt;MatchData API&lt;br /&gt;http://www.ruby-doc.org/core/classes/MatchData.html&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Shortcut to capture groups&lt;/strong&gt;&lt;br /&gt;If you only want to pick one section out from a string, there is a quick way to do it. Both of these will pick out a number that follows a space, but the second way is much more conmcise.&lt;br /&gt;&lt;code&gt;# The usual way&lt;br /&gt;md = s.match(/ ([0-9]+)/)&lt;br /&gt;p md.nil? ? nil : md[1]&lt;br /&gt;&lt;br /&gt;# The quick way&lt;br /&gt;p s[/ ([0-9]+)+/, 1]&lt;/code&gt;&lt;br /&gt;Note that for the first method we have to check for nil (no match is found), otherwise you will throw an error, as you are calling [] on nil. The quick way just returns nil if there is no match.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Back-references to capture groups - or not&lt;/strong&gt;&lt;br /&gt;A captured group can be refered to later in the pattern. Here is an example:&lt;br /&gt;&lt;pre&gt;pattern = /aa(\d+)-\1/&lt;br /&gt;pattern =~ 'aa1234-1234' # =&gt; 0&lt;br /&gt;pattern =~ 'aa1234-1233' # =&gt; nil&lt;/pre&gt;&lt;br /&gt;The pattern requires at least one digit inside the brackets. This is the capture group. The backslash-one refers back to this group, and requires that the exact same number is repeated.&lt;br /&gt;&lt;br /&gt;Note that capture groups number from one, rather than zero.&lt;br /&gt;&lt;br /&gt;You may not want to have back-references to your capture group  (remembering that you are limited to only 9 back-references). In the next example, question-mark-colon is used to indicate that we want to capture a group, but not to count it for back reference. We are looking for three groups of numbers in the pattern. The third should be identical to the second, but by marking the first as not counted, we can use \1 instead of \2. This trick allows you to have any number of captures, despite being limited to only nine back references.&lt;br /&gt;&lt;pre&gt;pattern = /(?:\d+)-(\d+)-\1/&lt;br /&gt;s = 'bird-cat-12-654-654-otter'&lt;br /&gt;match = pattern.match s&lt;br /&gt;match.to_a.each { |e| p e }&lt;br /&gt;# =&gt; "12-654-654"&lt;br /&gt;# =&gt; "654"&lt;br /&gt;# =&gt; "done"&lt;/pre&gt;&lt;br /&gt;If you use the String.scan method, it splits a string into an array, each member of which matches the given pattern. If the pattern includes a capture group, then it is the part that is captured that goes into the array. However, if you use ?: yoiu can stop that behavior, to get the whole match (or another capture).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Multiple matches&lt;/strong&gt;&lt;br /&gt;Often you want to match multiple occurances.&lt;br /&gt;&lt;pre&gt;\d       Match exactly one digits&lt;br /&gt;\d?      Match one or zero digits&lt;br /&gt;\d*      Match zero or more digits&lt;br /&gt;\d+      Match 1 or more digits&lt;br /&gt;\d{2,5}  Match between 2 and 5 digits&lt;br /&gt;aeiou*   Match "aeio" followed by any number of "u"&lt;br /&gt;[aeiou]* Match any number of vowels&lt;br /&gt;(aeiou)* Match any number of sequences of "aeiou"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Greedy vs non-greedy&lt;/strong&gt;&lt;br /&gt;A greedy match will try to match against as many characters as possible, while a non-greedy will match against as few as possible. Here is a simple example to illustrate:&lt;br /&gt;&lt;pre&gt;s = "Here another string"&lt;br /&gt;greedy = /[a-z]* [a-z]*/&lt;br /&gt;non_greedy = /[a-z]*? [a-z]*?/&lt;br /&gt;p greedy.match(s)[0]     # =&gt; "ere another"&lt;br /&gt;p non_greedy.match(s)[0] # =&gt; "ere "&lt;/pre&gt;&lt;br /&gt;The * will match against a number (or zero) of the preceding, so in the two Regexp objects, they will look for a match against a group of letters, then a space, then a group of letters. The difference is the second has the ?, which makes the * non-greedy.&lt;br /&gt;&lt;br /&gt;In both cases they ignore "H" as it does not fit, then they find a match for "e". The match continues, as both are allowed a variable number of letters, and they then match the space. Finally each can have a variable number of lower case letters. The non-greedy version aims for the fewest - in this case zero. The greedy version grabs all it can, so gets "another".&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Alternatives&lt;/strong&gt;&lt;br /&gt;For a set of alternative characters, put them inside square brackets. For sequences, use curved brackets, separated by vertical bars.&lt;br /&gt;&lt;pre&gt;[aeiou]   Match any one vowel&lt;br /&gt;(dog|cat) Match either "dog" or "cat"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Building Regexp objects dynamically&lt;/strong&gt;&lt;br /&gt;You can use #{} when defining a Regexp, just as you can for a double-quoted string. Here is a real example that adds two new methods to the String class (the Rails API already adds them, by the way):&lt;br /&gt;&lt;pre&gt;class String&lt;br /&gt;def starts_with? sub&lt;br /&gt;match(/^#{sub}/)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def ends_with? sub&lt;br /&gt;match(/#{sub}$/)&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The argument sent to the method gets incorporated into the Regexp. Note how ^ and $ are used to anchor the match to the start of the end of the string respectively.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Case sensitivity and other options&lt;/strong&gt;&lt;br /&gt;You can change the way the pattern matches either by appending a control code, to change the whole pattern, or using extended patterns (borrowed from Perl). These are things you can insert into a pattern inside brackets, following a question mark. For example, you can use i and -i to turn case sensitivity on and off.&lt;br /&gt;&lt;pre&gt;# Case sensitive by default&lt;br /&gt;pattern1 = /fox-cat-dog/&lt;br /&gt;pattern1 =~ 'fox-cat-dog' # =&gt; 0&lt;br /&gt;pattern1 =~ 'fox-CaT-dog' # =&gt; nil&lt;br /&gt;pattern1 =~ 'fox-CaT-doG' # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Whole pattern modified, case insensitive&lt;br /&gt;pattern2 = /fox-cat-dog/i&lt;br /&gt;pattern2 =~ 'fox-cat-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-doG' # =&gt; 0&lt;br /&gt;&lt;br /&gt;# Pattern behavior modified within the pattern&lt;br /&gt;# case sensitivity turned off then back on&lt;br /&gt;pattern2 = /fox-(?i)cat-(?-i)dog/&lt;br /&gt;pattern2 =~ 'fox-cat-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-doG' # =&gt; nil&lt;br /&gt;&lt;br /&gt;# Pattern behavior modified within the pattern&lt;br /&gt;# case sensitivity turned off for substring&lt;br /&gt;pattern2 = /fox-(?i:cat)-dog/&lt;br /&gt;pattern2 =~ 'fox-cat-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-dog' # =&gt; 0&lt;br /&gt;pattern2 =~ 'fox-CaT-doG' # =&gt; nil&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The full list of options is:&lt;br /&gt;&lt;pre&gt;/i         case insensitive&lt;br /&gt;/m         multiline mode - '.' will match newline&lt;br /&gt;/x         extended mode - whitespace is ignored&lt;br /&gt;/o         only interpolate #{} blocks once&lt;br /&gt;/[neus]    encoding: none, EUC, UTF-8, SJIS, respectively&lt;/pre&gt;&lt;br /&gt;The last two can, I think, only be used to modify the whole pattern.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Comments&lt;/strong&gt;&lt;br /&gt;There are various other options using the brackets-question-mark notation. You can embed a comment:&lt;br /&gt;&lt;pre&gt;pattern2 = /cat(?#comment)dog/&lt;br /&gt;pattern2 =~ 'catdog' # =&gt; 0&lt;/pre&gt;&lt;br /&gt;This makes more sense with the x option just mentioned, which causes the pattern to ignore whitespace, and so allow formatting and comments like this:&lt;br /&gt;&lt;pre&gt;pattern1 = /\d\d\d   (?# Looking for three digits  )&lt;br /&gt;        -        (?# followed by a hash        )&lt;br /&gt;        \d\d\d   (?# and abother three digits  )&lt;br /&gt;       /x&lt;br /&gt;p pattern1.match('578 123-678ref 567')[0]&lt;br /&gt;# =&gt; "123-678"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Looking ahead&lt;/strong&gt;&lt;br /&gt;You can also look ahead at what follows, without getting the next bit including in your match. You can check that  pattern is either there or is absent, as show in this example. In the first instance, pattern1 looks for three numbers follwed by "ref", but the resultant match has only the three numbers. Then pattern2 looks for three numbers not followed by a space.&lt;br /&gt;&lt;pre&gt;pattern1 = /\d\d\d(?=ref)/&lt;br /&gt;pattern2 = /\d\d\d(?! )/&lt;br /&gt;pattern3 = /\d?(?! )/&lt;br /&gt;p pattern1.match('578 123 678ref 567')[0]&lt;br /&gt;# =&gt; "678"&lt;br /&gt;p pattern2.match('578 123 678ref 567')[0]&lt;br /&gt;# =&gt; "678"&lt;br /&gt;p pattern3.match('578 123 678ref 567')[0]&lt;br /&gt;# =&gt; "57"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;And also...&lt;/strong&gt;&lt;br /&gt;One final option:&lt;br /&gt;&lt;pre&gt;(?&gt;)          nested anchored sub-regexp. stops backtracking.&lt;/pre&gt;&lt;br /&gt;Means nothing to me, but I mention it for completeness.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4900065528322587472?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4900065528322587472/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4900065528322587472' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4900065528322587472'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4900065528322587472'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/05/regular-expressions-in-ruby.html' title='Regular Expressions in ruby'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5922001829774720901</id><published>2009-04-21T20:33:00.001+01:00</published><updated>2009-05-09T23:17:25.234+01:00</updated><title type='text'>Using JavaScript with Ruby on Rails</title><content type='html'>Okay, this is a blog about Ruby and Rails, however, there are occasions when you want to do some processing at the client end, and JavaScript is the usual language to do that with. It is pretty straightforward to add JavaScript to your Rails web application. The strategy I employ is to write a static web page with the script on it, and get that working, and then transfer that to the Rails view.&lt;br /&gt;&lt;br /&gt;One imortant time to use JavaScript is for user-defined code. You can save the code to your database, for use later. But rather than invoke it in Ruby on your server (which is going to be a big security risk), use JavaScript on the client machine instead. Here are a couple of examples that I have used.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Moving the focus&lt;/strong&gt;&lt;br /&gt;This script will more the focus to the first text field or text area form element on the page (after checking that there is a form). I have this in my application-wide layout, so the focus gets set for every form in my application.&lt;br /&gt;&lt;pre&gt;&amp;lt;script&gt;&lt;br /&gt;// Sets the form focus to the first element found in forms[0] that&lt;br /&gt;// is a textfield or text area&lt;br /&gt;function setFocus() {&lt;br /&gt;// Bail if no form on page&lt;br /&gt;if (document.forms[0] == null) return;&lt;br /&gt;&lt;br /&gt;// Iterate though elements&lt;br /&gt;for (var i = 0; i &amp;lt; document.forms[0].elements.length; i++) {&lt;br /&gt;  e = document.forms[0].elements[i];&lt;br /&gt;  if ((e.type == "text") || (e.type == "textarea")) {&lt;br /&gt;    e.focus();&lt;br /&gt;    break;&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&amp;lt;/script&gt;  &lt;br /&gt;&lt;br /&gt;&amp;lt;body onload="setFocus()"&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Two buttons to add default values&lt;/strong&gt;&lt;br /&gt;First some background: This was for a table of laboratory samples. Occasionally, analysis is not required, and I wanted a quick way to note that in the comments text area. This helper method adds a link; click on it and the text is added to the text area.&lt;br /&gt;&lt;pre&gt;def not_required_button&lt;br /&gt;js = "sample_comments.value += \'Not required.\'"&lt;br /&gt;"&amp;lt;a onclick=\"#{js}\" class=\"not-button\"&gt;[n/r]"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The method builds a little string of JavaScript, and then uses that in some HTML. I set up the CSS class like this:&lt;br /&gt;&lt;pre&gt;a.not-button {&lt;br /&gt;color: silver;&lt;br /&gt;font-size: 10px;&lt;br /&gt;cursor: pointer;&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The next example is a bit more complicated. Again this was for the table of laboratory samples, and there are several different types of samples requiring different fields. To handle that, I created an array of hashes; each hash held the information for one field (for example, how to display it). The edit and show actions iterate through the array, and display the fields based on the values in the hash. Several fields usually require the next number in a sequence, so what I wanted was a button the user could click to add that number. This helper method does just that:&lt;br /&gt;&lt;pre&gt;def count_button field&lt;br /&gt;return '' if !field[:count]&lt;br /&gt;old_value = Sample.maximum field[:column_name]&lt;br /&gt;js = "#{sample_#{field[:column_name]}}.value = \'#{old_value.nil? ? 1 : old_value + 1}\'"&lt;br /&gt;"&amp;lt;input type=\"button\" onclick=\"#{js}\" value=\"\#\"}&gt;"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The method accepts the hash for the field as a parameter. If the value of count is not set to true, then no button is wanted, and the method returns. Otherwise, it searches the Sample table for the highest value already there, and adds one to that (or uses one as the value if there are none there yet). Then it builds the JavaScript, in the string js. The tricky bit is working out what JavaScript will expect the element to be called; the convention is class_column, all in lowercase and underscored (you can confirm that by looking at the HTML source of your output page, of course). The JavaScript code is in turn is put into the HTML code for the button.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5922001829774720901?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5922001829774720901/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5922001829774720901' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5922001829774720901'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5922001829774720901'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/04/using-javascript-with-ruby-on-rails.html' title='Using JavaScript with Ruby on Rails'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-2885889510410344935</id><published>2009-03-23T20:26:00.005Z</published><updated>2009-04-21T09:43:43.744+01:00</updated><title type='text'>The Model Part 5 - Find and other ActiveRecord methods</title><content type='html'>&lt;strong&gt;The find method&lt;/strong&gt;&lt;br /&gt;ActiveRecord provides a lot of functionality through the find method and its derivatives. Here are some examples:&lt;br /&gt;&lt;pre&gt;Post.find 45&lt;br /&gt;# Retrieves the post with id=45&lt;br /&gt;Post.find 2, 4, 5&lt;br /&gt;# Gets the posts with id equal to 2, 4 and 5 (as an array)&lt;br /&gt;Post.find :first&lt;br /&gt;# Retrieves the first post in the database&lt;br /&gt;Post.find :last&lt;br /&gt;# Retrieves the last post in the database&lt;br /&gt;Post.find :all&lt;br /&gt;# Retrieves all the posts (as an array)&lt;br /&gt;Post.find_by_author 'F2Andy'&lt;br /&gt;# Retrieves the first post in the database authored by F2Andy&lt;br /&gt;Post.find_all_by_author 'F2Andy'&lt;br /&gt;# Retrieves all the posts in the database authored by F2Andy&lt;br /&gt;Post.find_all_by_author_and_title 'F2Andy', 'ActiveRecord find'&lt;br /&gt;Post.find :all, conditions =&gt; { :title =&gt; 'ActiveRecord find',&lt;br /&gt;                             :author =&gt; 'F2Andy'}&lt;br /&gt;# Both these retrieves all the posts in the database with&lt;br /&gt;# the given author and title&lt;/pre&gt;&lt;br /&gt;There are various options you can include in your search, as illustrated here, which gets the 21st through to 30th posts, ordered by the title:&lt;br /&gt;&lt;pre&gt;Post.find_all_by_author 'F2Andy', :order =&gt; 'title',&lt;br /&gt;                    :offset =&gt; 20, :limit =&gt; 10&lt;/pre&gt;&lt;br /&gt;You can determine whether the ordering goes up or down using ASC and DESC (defaults to ASC). The offset is ignored if limit is not present.&lt;br /&gt;&lt;br /&gt;When you know what you are searching for, ActiveRecord has it covered. However, often we do not. Do a search of Google, and you are looking for one or more words within the text. To do that for ActiveRecord you need to delve into SQL a little.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Dipping a Toe into SQL&lt;/strong&gt;&lt;br /&gt;Rails helps you to some degree, and to see how, let us perform that last search again.&lt;br /&gt;&lt;pre&gt;Post.find :all, :conditions =&gt; ['author = ? AND title = ?',&lt;br /&gt;                     'F2Andy', 'ActiveRecord find']&lt;/pre&gt;&lt;br /&gt;Notice the &lt;code&gt;:conditions&lt;/code&gt; key. This maps to an array. The first element is the base string, some SQL code including question marks. All the other elements are substituted for the question marks in order. The SQL command that is used will be something like:&lt;br /&gt;&lt;pre&gt;SELECT * FROM Post WHERE author = "F2Andy" AND&lt;br /&gt;                       title = "ActiveRecord find"&lt;/pre&gt;&lt;br /&gt;You can use symbols rather than question marks. It is a little more long-winded, but makes it clear what goes where, and you can go in any order, so would be preferable in all but the simplest of cases.&lt;br /&gt;&lt;pre&gt;Post.find :all,&lt;br /&gt;:conditions =&gt; ['author = :author AND title = :title?',&lt;br /&gt;:author =&gt; 'F2Andy', :title =&gt; 'ActiveRecord find'}]&lt;/pre&gt;&lt;br /&gt;ActiveRecord does some kind of sanitising to protect against SQL injection attacks. While the following will work, it is a bad idea, as it will bypass that process:&lt;br /&gt;&lt;pre&gt;Post.find :all,&lt;br /&gt; :conditions =&gt; 'author = "F2Andy" AND title = "ActiveRecord find"'&lt;br /&gt;Post.find_by_sql 'SELECT * FROM Post WHERE author = "F2Andy" AND title = "ActiveRecord find"'&lt;/pre&gt;&lt;br /&gt;However, for complex searches, this might be your only option (an interesting page on that can be seen &lt;a href="http://www.edwardthomson.com/blog/2007/02/complex_sql_queries_with_rails.html"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using Wildcards&lt;/strong&gt;&lt;br /&gt;So now we are ready to search for a fragment within a field. In SQL, you use the LIKE keyword, rather than the equals sign, and use % as a wildcard. Let us suppose I have a database of literature references, and I am searching for one author, Smith.&lt;br /&gt;&lt;pre&gt;refs = Ref.find :all,&lt;br /&gt; :conditions =&gt; [ "authors LIKE ?", "%Smith%" ]&lt;/pre&gt;&lt;br /&gt;This will return any record where "Smith" appears in the authors field.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Case Insensitive&lt;/strong&gt;&lt;br /&gt;There is no standard for doing case sensitive/insensitive seaches in SQL (and no help from Rails either), nor any standard about which should be the default (indeed, that depends on how the database is set up).&lt;br /&gt;&lt;br /&gt;On PostgreSQL, you can use &lt;code&gt;ILIKE&lt;/code&gt; to do case insensitive searches:&lt;br /&gt;&lt;pre&gt;refs = Ref.find :all,&lt;br /&gt; :conditions =&gt; [ "authors ILIKE ?", "%smith%" ]&lt;/pre&gt;&lt;br /&gt;On MySQL, you can change the collaton method (this seems to be the usual SQL strategy, however as each database system has its own collations, it still varies between databases; SQL Server uses &lt;code&gt;SQL_Latin1_General_CP1_CI_AS&lt;/code&gt; I think).&lt;br /&gt;&lt;pre&gt;refs = Ref.find :all,&lt;br /&gt; :conditions =&gt; [ "authors LIKE ? COLLATE utf8_general_ci",&lt;br /&gt;                   "%smith%" ]&lt;/pre&gt;&lt;br /&gt;What this all means is that the only safe way is to convert to all lower (or upper) case. The only way I could get this to work was to change the search term before hand (possibly due to how Rails sanitises the SQL).&lt;br /&gt;&lt;pre&gt;term = "Smith".downcase&lt;br /&gt;refs = Ref.find :all,&lt;br /&gt; :conditions =&gt; [ "LOWER(authors) LIKE ?", "%#{term}%" ]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Complicated searches&lt;/strong&gt;&lt;br /&gt;So what if we want to search for muliple words in multiple fields? What you need to do is build a search string that each term with be put into, and an array of terms. Here is an addition to ActiveRecord::Base that will do just that.&lt;br /&gt;&lt;pre&gt;class ActiveRecord::Base&lt;br /&gt;# Retrieves all ActiveRecords that contain the&lt;br /&gt;# user supplied keywords.&lt;br /&gt;# The hash parameter should contain column name&lt;br /&gt;# mappings to strings of keywords. For example:&lt;br /&gt;#  refs = Ref.search :authors =&gt; 'smith jones',&lt;br /&gt;#                   :body =&gt; 'ruby search'&lt;br /&gt;# This will retrieve any record containing both&lt;br /&gt;# "smith" and "jones" in the authors field, and&lt;br /&gt;# "ruby" and "search" in the body field.&lt;br /&gt;# The search is case insensitive.&lt;br /&gt;# Note that simply sending the params hash from&lt;br /&gt;# the controller will not work, as this includes&lt;br /&gt;# values for :action and :controller.&lt;br /&gt;def self.search params&lt;br /&gt; # This will becomes the base for the SQL string&lt;br /&gt; sql_fragments = []&lt;br /&gt; # This is the array of search terms. The first&lt;br /&gt; #entry is just a place holder; this will be&lt;br /&gt; # replaced by the SQL string at the end.&lt;br /&gt; search_terms = ['']&lt;br /&gt; params.each_pair do |k, v|&lt;br /&gt;   v.split.each do |e|&lt;br /&gt;     sql_fragments &amp;lt;&amp;lt; "LOWER(#{k.to_s}) LIKE ?"&lt;br /&gt;     search_terms &amp;lt;&amp;lt; "%#{e.downcase}%"&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt; # Now assemble the SQL string and put it at&lt;br /&gt; # the start of the array of terms.&lt;br /&gt; search_terms[0] = sql_fragments.join(' AND ')&lt;br /&gt; find :all, :conditions =&gt; search_terms&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Other methods&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The delete and destroy methods&lt;/em&gt;&lt;br /&gt;These take an id or an array of ids to delete a set of records, returning the number of records set. The destroy method actually creates a new instance, populates it with data from the table, then calls the destroy method on the object, so will be slower, but will ensure any custom code in the destroy method and any callbacks and filters is invoked.&lt;br /&gt;&lt;pre&gt;Post.delete 19&lt;br /&gt;Post.destroy [23, 67, 103]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The delete_all and destroy_all methods&lt;/em&gt;&lt;br /&gt;These are similar to find :all, and will accept the same sort of conditions. As with delete and destroy, destroy_all is slower as the objects are instantiated first.&lt;br /&gt;&lt;pre&gt;Post.delete_all :conditions =&gt; [ "user_name = ? AND category = ?",&lt;br /&gt;    user_name, category ]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The exists? method&lt;/em&gt;&lt;br /&gt;This method returns true if one or more records matching the condition exists. Note that it accepts either an id, or the condition itself (rather than :condition mapping to the condition)&lt;br /&gt;&lt;pre&gt;Post.exists? 45&lt;br /&gt;Post.exists? :user_name =&gt; user_name, :category =&gt; category&lt;br /&gt;Post.exists? ["user_name = ? AND category = ?",&lt;br /&gt;                   user_name, category]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Calculations&lt;/em&gt;&lt;br /&gt;As well as retrieving records, you can perform calculations, using average, maximum, minimum and sum. Examples from the API:&lt;br /&gt;&lt;pre&gt;Person.calculate(:count, :all) # The same as Person.count&lt;br /&gt;Person.average(:age) # SELECT AVG(age) FROM people...&lt;br /&gt;Person.minimum(:age,&lt;br /&gt; :conditions =&gt; ['last_name != ?', 'Drake'])&lt;br /&gt;# Selects the minimum age for everyone with a last name other&lt;br /&gt;# than 'Drake'&lt;br /&gt;Person.minimum(:age, :having =&gt; 'min(age) &gt; 17',&lt;br /&gt; :group =&gt; :last_name)&lt;br /&gt;# Selects the minimum age for any family without any minors&lt;br /&gt;Person.sum("2 * age")&lt;/pre&gt;&lt;br /&gt;You can also use count. Again, examples from the API:&lt;br /&gt;&lt;pre&gt;Person.count&lt;br /&gt;# returns the total count of all people&lt;br /&gt;Person.count(:age)&lt;br /&gt;# returns the total count of all people&lt;br /&gt;# whose age is present in database&lt;br /&gt;Person.count(:conditions =&gt; "age &gt; 26")&lt;br /&gt;Person.count(:conditions =&gt; "age &gt; 26 AND job.salary &gt; 60000",&lt;br /&gt; :include =&gt; :job)&lt;br /&gt;# because of the named association, it finds the DISTINCT&lt;br /&gt;# count using LEFT OUTER JOIN.&lt;br /&gt;Person.count(:conditions =&gt; "age &gt; 26 AND job.salary &gt; 60000",&lt;br /&gt; :joins =&gt; "LEFT JOIN jobs on jobs.person_id = person.id")&lt;br /&gt;# finds the number of rows matching the conditions and joins.&lt;br /&gt;Person.count('id', :conditions =&gt; "age &gt; 26")&lt;br /&gt;# Performs a COUNT(id)&lt;br /&gt;Person.count(:all, :conditions =&gt; "age &gt; 26")&lt;br /&gt;# Performs a COUNT(*) (:all is an alias for '*')&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html"&gt;http://api.rubyonrails.org/classes/ActiveRecord/Base.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html"&gt;http://api.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Reference:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html"&gt;http://api.rubyonrails.org/classes/ActiveRecord/Base.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-2885889510410344935?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/2885889510410344935/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=2885889510410344935' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2885889510410344935'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2885889510410344935'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/03/model-part-4-find-other-activerecord.html' title='The Model Part 5 - Find and other ActiveRecord methods'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-6780428983355190448</id><published>2009-03-18T21:30:00.000Z</published><updated>2009-03-18T21:38:37.817Z</updated><title type='text'>Ruby dates and times</title><content type='html'>Ruby has three classes for handling time, &lt;code&gt;Date&lt;/code&gt;, &lt;code&gt;DateTime&lt;/code&gt; and &lt;code&gt;Time&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Time&lt;/code&gt; is part of the core language, while &lt;code&gt;Date&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; are part of  standard Ruby; to use &lt;code&gt;Date&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; you will need to load in &lt;code&gt;date.rb&lt;/code&gt;. Here is some code that initialises each with the current date/time.&lt;br /&gt;&lt;pre&gt;t = Time.now&lt;br /&gt;# =&gt; Fri Feb 06 08:56:27 +0000 2009&lt;br /&gt;require 'date'  # Needed for Date and DateTime&lt;br /&gt;# =&gt; true&lt;br /&gt;d = Date.today&lt;br /&gt;# =&gt; #&amp;lt;Date: 4909737/2,0,2299161&gt;&lt;br /&gt;dt = DateTime.now&lt;br /&gt;# =&gt; #&amp;lt;DateTime: 14140044704711/5760000,0,2299161&gt;&lt;/pre&gt;&lt;br /&gt;As you can see, despite its name, the &lt;code&gt;Time&lt;/code&gt; class holds the date as well as the time. The &lt;code&gt;inspect&lt;/code&gt; method of &lt;code&gt;Time&lt;/code&gt; gives a convenient output; not so &lt;code&gt;Date&lt;/code&gt; or &lt;code&gt;DateTime&lt;/code&gt;. However, the &lt;code&gt;to_s&lt;/code&gt; method is a little more useful. The best option is to use the &lt;code&gt;strftime&lt;/code&gt; method for all of them, which gives you full control over how time and dates are formated.&lt;br /&gt;&lt;pre&gt;p t.inspect&lt;br /&gt;# =&gt; "Fri Feb 06 08:56:27 +0000 2009"&lt;br /&gt;p d.inspect&lt;br /&gt;# =&gt; "#&lt;date: 4909737="" 2299161=""&gt;"&lt;br /&gt;p t.to_s&lt;br /&gt;# =&gt; "Fri Feb 06 08:56:27 +0000 2009"&lt;br /&gt;p d.to_s&lt;br /&gt;# =&gt; "2009-02-06"&lt;br /&gt;p dt.to_s&lt;br /&gt;# =&gt; "2009-02-06T08:56:10+00:00"&lt;br /&gt;p d.strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 06/Feb/09"&lt;br /&gt;p t.strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0856 on 06/Feb/09"&lt;br /&gt;p dt.strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0856 on 06/Feb/09"&lt;/date:&gt;&lt;/pre&gt;&lt;br /&gt;The full list of options (from &lt;a href="http://www.techotopia.com/index.php/Working_with_Dates_and_Times_in_Ruby"&gt;here&lt;/a&gt;):&lt;br /&gt;&lt;pre&gt;  %a - The abbreviated weekday name ("Sun")&lt;br /&gt; %A - The  full  weekday  name ("Sunday")&lt;br /&gt; %b - The abbreviated month name ("Jan")&lt;br /&gt; %B - The  full  month  name ("January")&lt;br /&gt; %c - The preferred local date and time representation&lt;br /&gt; %d - Day of the month (01..31)&lt;br /&gt; %H - Hour of the day, 24-hour clock (00..23)&lt;br /&gt; %I - Hour of the day, 12-hour clock (01..12)&lt;br /&gt; %j - Day of the year (001..366)&lt;br /&gt; %m - Month of the year (01..12)&lt;br /&gt; %M - Minute of the hour (00..59)&lt;br /&gt; %p - Meridian indicator ("AM" or "PM")&lt;br /&gt; %S - Second of the minute (00..60)&lt;br /&gt; %U - Week  number  of the current year,&lt;br /&gt;         starting with the first Sunday as the first&lt;br /&gt;         day of the first week (00..53)&lt;br /&gt; %W - Week  number  of the current year,&lt;br /&gt;         starting with the first Monday as the first&lt;br /&gt;         day of the first week (00..53)&lt;br /&gt; %w - Day of the week (Sunday is 0, 0..6)&lt;br /&gt; %x - Preferred representation for the date alone, no time&lt;br /&gt; %X - Preferred representation for the time alone, no date&lt;br /&gt; %y - Year without a century (00..99)&lt;br /&gt; %Y - Year with century&lt;br /&gt; %Z - Time zone name&lt;br /&gt; %% - Literal "%" character&lt;/pre&gt;&lt;br /&gt;You can also create &lt;code&gt;Date&lt;/code&gt;, &lt;code&gt;Time&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; objects using the &lt;code&gt;new&lt;/code&gt; method. &lt;code&gt;Date&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; default to midnight on the 1st of January 1988, while &lt;code&gt;Time&lt;/code&gt; defaults to the current date and time. With &lt;code&gt;Date&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; you can set specific values. The parameter list starts with the biggest units, years, and gets smaller. Successive arguments are optional.&lt;br /&gt;&lt;pre&gt;p Date.new.strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 01/Jan/88"&lt;br /&gt;p DateTime.new.strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 01/Jan/88"&lt;br /&gt;p Date.new(2006).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 01/Jan/06"&lt;br /&gt;p Date.new(2006, 4).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 01/Apr/06"&lt;br /&gt;p Date.new(2006, 4, 7).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 07/Apr/06"&lt;br /&gt;p DateTime.new(2006, 4, 7).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0000 on 07/Apr/06"&lt;br /&gt;p DateTime.new(2006, 4, 7, 8).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0800 on 07/Apr/06"&lt;br /&gt;p DateTime.new(2006, 4, 7, 8, 23).strftime('%H%M on %d/%b/%y')&lt;br /&gt;# =&gt; "0823 on 07/Apr/06"&lt;/pre&gt;&lt;br /&gt;Using date and time examples.&lt;br /&gt;&lt;pre&gt;d2 = d1 &gt;&gt; 2  # d2 will be two months later than d1&lt;br /&gt;d2 = d1 &amp;lt;&amp;lt; 2  # d2 will be two months earlier than d1&lt;br /&gt;d.month&lt;br /&gt;dt.day&lt;br /&gt;d.wday  # Day of week, Monday = 1&lt;br /&gt;d.yday # Day of the year&lt;br /&gt;d.zone # Time zone&lt;br /&gt;d.leap?  # Leap year?&lt;br /&gt;dt.hour&lt;br /&gt;dt.min&lt;br /&gt;dt.sec&lt;br /&gt;dt.sec_fraction&lt;/pre&gt;&lt;br /&gt;You can determine the different between two dates just be taking one from the other. The complication is that the result is a Rational.&lt;br /&gt;&lt;pre&gt;d1 = Date.new 2004&lt;br /&gt;d2 = Date.new 2005&lt;br /&gt;d2 - d1&lt;br /&gt;# =&gt; Rational(366, 1)&lt;/pre&gt;&lt;br /&gt;A &lt;code&gt;Rational&lt;/code&gt; object consists of two numbers. Basically it is a fraction; the first number goes on top, the second number of the bottom (in mathematics, a rational number is one that can be expressed as a faction with finite digits; as opposed to, for example, pi, which is an irrational number). The number of days between the 1st January 2004 and 2005 is 366 divided by 1. You can freely use &lt;code&gt;Date&lt;/code&gt; and &lt;code&gt;DateTime&lt;/code&gt; objects together; the result is always the number of days expressed as a fraction, as a &lt;code&gt;Rational&lt;/code&gt; object. You can convert your &lt;code&gt;Rational&lt;/code&gt; object to an array cotaining the hours, minutes, second and the second fraction with &lt;code&gt;Date.day_fraction_to_time&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;According to &lt;a href="http://www.blogger.com/post-create.do" edu="" reeset="" blog="" archives="" 399=""&gt;here&lt;/a&gt;, &lt;code&gt;Time&lt;/code&gt; is written in C, and is therefore some 20 times faster than &lt;code&gt;Date&lt;/code&gt;/&lt;code&gt;DateTime&lt;/code&gt;. However, it can only handle dates from 1970 to 2039 (Unix epoch)&lt;br /&gt;&lt;br /&gt;Humanize time/date:&lt;br /&gt;&lt;a href="http://www.i76.nl/weblog/ruby-date-time"&gt;http://www.i76.nl/weblog/ruby-date-time&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-6780428983355190448?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/6780428983355190448/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=6780428983355190448' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6780428983355190448'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6780428983355190448'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/03/ruby-dates-and-times.html' title='Ruby dates and times'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-8265137943311652671</id><published>2009-03-15T10:42:00.002Z</published><updated>2009-05-11T11:58:03.887+01:00</updated><title type='text'>Accessors</title><content type='html'>In Ruby, variables are always private; they cannot be directly accessed from outside the object (constants are always public). However, it is often the case that you do need to allow some access. One way would be to define methods that set and get the values. For example:&lt;br /&gt;&lt;pre&gt;class TestClass&lt;br /&gt;def initialize id, name&lt;br /&gt;  @id = id&lt;br /&gt;  @name = name&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def id&lt;br /&gt;  @id&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def name&lt;br /&gt;  @name&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def name= s&lt;br /&gt;  @name = s&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Test it works properly&lt;br /&gt;tc = TestClass.new 12, 'Boris'&lt;br /&gt;p tc.id&lt;br /&gt;p tc.name&lt;br /&gt;tc.name = 'Alfie'&lt;br /&gt;p tc.name&lt;/pre&gt;&lt;br /&gt;Note that the id cannot be set after the object is created; it is a read-only attribute.&lt;br /&gt;&lt;br /&gt;Ruby offers a short cut for getters and setters. The above class can be re-written like this:&lt;br /&gt;&lt;pre&gt;class TestClass&lt;br /&gt;def initialize id, name&lt;br /&gt;  @id = id&lt;br /&gt;  @name = name&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;attr_reader :id&lt;br /&gt;attr_accessor :name&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The class behaves just the same, so the test code will work here as well, but all that clutter has been removed.&lt;br /&gt;&lt;br /&gt;There is also a method for write-only attributes, and several attributes can be listed, separated with commas:&lt;br /&gt;&lt;pre&gt;attr_reader :size, :address, :dir&lt;/pre&gt;&lt;br /&gt;What is happening is that &lt;code&gt;attr_reader&lt;/code&gt; is a method (in the &lt;a href="http://www.ruby-doc.org/core-1.9/classes/Module.html#M001292"&gt;&lt;code&gt;Module&lt;/code&gt;&lt;/a&gt; class), that takes the parameter &lt;code&gt;:id&lt;/code&gt;, and dynamically defines the &lt;code&gt;id&lt;/code&gt; method.&lt;br /&gt;&lt;br /&gt;Having said that, here is an interesting article (written for Java, but applicable to any object-orientated language) about why getters and setters are evil (sometimes):&lt;br /&gt;&lt;a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html"&gt;http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-8265137943311652671?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/8265137943311652671/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=8265137943311652671' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8265137943311652671'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8265137943311652671'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/03/accessors.html' title='Accessors'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5518014582597677918</id><published>2009-03-14T08:40:00.000Z</published><updated>2009-03-14T08:41:02.163Z</updated><title type='text'>Constants</title><content type='html'>The Ruby interpreter will take anything that has a name beginning with a capital letter as being a constant.&lt;br /&gt;&lt;pre&gt;# Variables&lt;br /&gt;n = 67&lt;br /&gt;s = 'my string'&lt;br /&gt;&lt;br /&gt;#Constants&lt;br /&gt;N = 89&lt;br /&gt;TITLE = 'My great program'&lt;br /&gt;class MyClass end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Not really constant?&lt;/strong&gt;&lt;br /&gt;Variables and constants are really pointers to objects. This has some practical consequences that may be unexpected. Let us set some up:&lt;br /&gt;&lt;pre&gt;S = s = 'My string'&lt;br /&gt;N = n = 23&lt;br /&gt;X = x = 12.6&lt;/pre&gt;&lt;br /&gt;Then we can see what happens what we modify the object:&lt;br /&gt;&lt;pre&gt;s &amp;lt;&amp;lt; ' is longer'&lt;br /&gt;n += 4&lt;br /&gt;x += 3.5&lt;/pre&gt;&lt;br /&gt;Perhaps the odd thing here is that modifying s also modifies the constant, S. But is that so odd? Both s and S point to the same string. Modify the string, and naturally what they both point to has changed. So what is surprising is that the others have not changed (as an aside, this is also the situation in Java, but in Java, numbers are primitives, not objects; in Ruby everything is an object). Numbers have one object each to represent each value (though they will not all exist in te virtual machine t any one time of course). Change the value, and it will point to a new instance that stands for the new value.&lt;br /&gt;&lt;br /&gt;Note that for the string, I used &amp;lt;&amp;lt; rather than +=. Although they both concatenate strings, The former changes the existing string, while the latter creates a new string. If I had used += in the above, s would change to point to the new string, while S would still point to the old string.&lt;br /&gt;&lt;br /&gt;So you can readily modify the object that a constant points to, but you cannot change what object it points to... Can you? Well, yes you can. The only issue is that the interpreter gives a warning. Here is an IRb session:&lt;br /&gt;&lt;pre&gt;irb(main):011:0&gt; Constant = 'My string'&lt;br /&gt;=&gt; "My string"&lt;br /&gt;irb(main):012:0&gt; Constant = 56&lt;br /&gt;(irb):12: warning: already initialized constant Constant&lt;br /&gt;=&gt; 56&lt;/pre&gt;&lt;br /&gt;It turns out that constants are only really constant by convention, and there is nothing to stop you changing them and no guarantee that they will remain the same (just as setting a method as private is no guarantee that it cannot be invoked from anywhere).&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5518014582597677918?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5518014582597677918/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5518014582597677918' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5518014582597677918'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5518014582597677918'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/03/constants.html' title='Constants'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5910551958830937999</id><published>2009-03-07T21:38:00.005Z</published><updated>2010-02-23T10:58:48.841Z</updated><title type='text'>Ruby blocks</title><content type='html'>A block is a chunk of code. What is great in Ruby is the way they can be passed as an argument to a method. For example, that is what is happening here:&lt;br /&gt;&lt;pre&gt;(0..10).each { |x|&lt;br /&gt;  p x&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The (0..10) is a Range object, with a method, &lt;code&gt;each&lt;/code&gt;. The method is passed the block (everything between the curly braces). Blocks can be defined with do and end, rather than curly braces (but note that the precedence is different).&lt;br /&gt;&lt;pre&gt;(0..10).each do |x|&lt;br /&gt;p x&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Implicitly passing blocks&lt;/strong&gt;&lt;br /&gt;Here is an example of passing a block to a custom method, &lt;code&gt;test&lt;/code&gt;. Note that &lt;code&gt;test&lt;/code&gt; does not mention the block at all, so the block is considered to have been passed implicitly. Where the block is used is with the &lt;code&gt;yield&lt;/code&gt; statement.&lt;br /&gt;&lt;pre&gt;def test&lt;br /&gt;  p yield(5, 'house')&lt;br /&gt;  p yield(100, 'mansion')&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test { |i, s|&lt;br /&gt;  puts "You are in the block #{i} #{s}"&lt;br /&gt;  "Returning #{i} #{s}"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;# Output:&lt;br /&gt;&lt;br /&gt;# You are in the block 5 house&lt;br /&gt;# "Returning 5 house"&lt;br /&gt;# You are in the block 100 mansion&lt;br /&gt;# "Returning 100 mansion"&lt;/pre&gt;&lt;br /&gt;So what is going on? The &lt;code&gt;test&lt;/code&gt; method is invoked, and passed a block of code. Inside the &lt;code&gt;test&lt;/code&gt; method, Ruby iterates though each line until it reaches a &lt;code&gt;yield&lt;/code&gt; statement, and when it does, it runs the code block passed to the method. The &lt;code&gt;yield&lt;/code&gt; statement is kind of like a method call, in that you can pass it arguments (and it will insist on the right number of arguments), and it can return a value too. You can think of &lt;code&gt;yield&lt;/code&gt; as an alias for your block, so in the above example, &lt;code&gt;yield&lt;/code&gt; is sent a number and a string, and returns a new string.&lt;br /&gt;&lt;br /&gt;Naturally the block will be run every time Ruby encounters a &lt;code&gt;yield&lt;/code&gt; statement, which is twice in the above example.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Iterating with blocks&lt;/strong&gt;&lt;br /&gt;Okay, now it gets a bit hairy, and web pages that actually address this become correspondingly rare...&lt;br /&gt;&lt;br /&gt;How do you get the method that is receiving a block to iterate over an Array or Hash? In this example, a method, &lt;code&gt;test&lt;/code&gt;, is added to the class &lt;code&gt;Array&lt;/code&gt;, then an &lt;code&gt;Array&lt;/code&gt; object is ceated and &lt;code&gt;test&lt;/code&gt; is invoked.&lt;br /&gt;&lt;pre&gt;class Array&lt;br /&gt;  def test&lt;br /&gt;    total = 0&lt;br /&gt;    each { |x|&lt;br /&gt;      p yield(5 + x)&lt;br /&gt;      total += x&lt;br /&gt;    }&lt;br /&gt;    total&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;ma = [12, 34, 8]&lt;br /&gt;p ma.test { |y|&lt;br /&gt;  p y&lt;br /&gt;  y - 5&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;# Output:&lt;br /&gt;&lt;br /&gt;# 17&lt;br /&gt;# 12&lt;br /&gt;# 39&lt;br /&gt;# 34&lt;br /&gt;# 13&lt;br /&gt;# 8&lt;br /&gt;# 54&lt;/pre&gt;&lt;br /&gt;The first point to note is the &lt;code&gt;each&lt;/code&gt; statement and its associated block. This is what allows us to iterate over the &lt;code&gt;Array&lt;/code&gt; (or &lt;code&gt;Hash&lt;/code&gt;). The &lt;code&gt;each&lt;/code&gt; statement sets up a variable, &lt;code&gt;x&lt;/code&gt;. This will take the value of each member of the array in turn, as normal. On the next line there is the &lt;code&gt;yield&lt;/code&gt; statement. This invokes the block that was received, sending it the current value from the array, plus five.&lt;br /&gt;&lt;br /&gt;The block is set up to accept a single value, and to call it &lt;code&gt;y&lt;/code&gt;, which it then prints. It then returns this value minus five.&lt;br /&gt;&lt;br /&gt;Back with the &lt;code&gt;yield&lt;/code&gt; statement, and the test method prints the returned value. Then it adds the current value from the array, &lt;code&gt;x&lt;/code&gt;, to the variable &lt;code&gt;total&lt;/code&gt;. Once the loop finishes (all the array members have been done), &lt;code&gt;total&lt;/code&gt; is used as a return value for the test method.&lt;br /&gt;&lt;br /&gt;Back outside the &lt;code&gt;test&lt;/code&gt; method, the returned value is printed.&lt;br /&gt;&lt;br /&gt;Here are more useful examples for the Array class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;class Array&lt;br /&gt;  # Allows you to loop over an array, accessing&lt;br /&gt;  # both the index and the value&lt;br /&gt;  def each_pair&lt;br /&gt;    each_index { |i| yield i, fetch(i) }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  # As the each method, but skips the first element&lt;br /&gt;  def each_not_first&lt;br /&gt;    each_index { |i| yield fetch(i) unless i == 0 }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  # Returns a total over each element in the array&lt;br /&gt;  # where the value for an element is determined&lt;br /&gt;  # by the given block.&lt;br /&gt;  def total &amp;amp;prc&lt;br /&gt;    val = 0&lt;br /&gt;    each { |e| val += prc.call(e) }&lt;br /&gt;    val&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  # Returns an element that best fits the criteria&lt;br /&gt;  # given by the block.&lt;br /&gt;  # Note that I have used yield here, it seems to work&lt;br /&gt;  # better if you have more than one parameter;&lt;br /&gt;  # "warning: multiple values for a block parameter..."&lt;br /&gt;  def find_best &amp;amp;prc&lt;br /&gt;    best = first&lt;br /&gt;    each_not_first { |e| best = e if yield(best, e) }&lt;br /&gt;    best&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Example array&lt;br /&gt;ary = [&lt;br /&gt;  {:name =&gt; 'one', :value =&gt; 56},&lt;br /&gt;  {:name =&gt; 'two', :value =&gt; 79},&lt;br /&gt;  {:name =&gt; 'three', :value =&gt; -5},&lt;br /&gt;]&lt;br /&gt;&lt;br /&gt;# This uses each_pair to print both the index,&lt;br /&gt;# and the name of the item.&lt;br /&gt;ary.each_pair { |index, item| "#{index}: #{item[:name]}" }&lt;br /&gt;&lt;br /&gt;# This example uses total to add up the&lt;br /&gt;# values of each element.&lt;br /&gt;p ary.total { |e| e[:value] }&lt;br /&gt;&lt;br /&gt;# This one uses find to get the element with the&lt;br /&gt;# highest value.&lt;br /&gt;p ary.find { |x, y| x[:value] &amp;lt; y[:value] }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Explicitly passing blocks&lt;/strong&gt;&lt;br /&gt;If you want to be able handle the block other than through &lt;code&gt;yield&lt;/code&gt;, you need to pass it explicitly. All this involves is listing it in the arguments. Note that the block must be last in the list, and has to be preceded by an ampersand (but the ampersand should not be present when used later in your code). When you do this, the block is converted to a &lt;code&gt;Proc&lt;/code&gt; object (which I discussed &lt;a href="http://strugglingwithruby.blogspot.com/2009/02/ruby-proc.html"&gt;here&lt;/a&gt;; note that you cannot pass a &lt;code&gt;Proc&lt;/code&gt; object in lieu of a block).&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def test &amp;amp;prc&lt;br /&gt;  puts "The block is of the #{prc.class} class"&lt;br /&gt;  puts prc.call('This') unless prc.nil?&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test { |s| "#{s} does nothing" }&lt;br /&gt;&lt;br /&gt;test&lt;br /&gt;&lt;br /&gt;# Output:&lt;br /&gt;&lt;br /&gt;# The block is of the Proc class&lt;br /&gt;# This does nothing&lt;br /&gt;# The block is of the NilClass class&lt;/pre&gt;&lt;br /&gt;Apparently, this is significantly slower than using implicit passing. The block is invoked with &lt;code&gt;call&lt;/code&gt;; arguments to that are passed to the block.&lt;br /&gt;&lt;br /&gt;Note that you cannot set a default value for a block in the arguments of method, however, as shown above, if no block is given the variable will be set to nil.&lt;br /&gt;&lt;br /&gt;Many languages have a 'with' statement (Visual BASIC and Pascal). This example adds that functionality to Ruby, and also compares explicit and implicit passing:&lt;br /&gt;&lt;pre&gt;# Define a complicated data struction&lt;br /&gt;data = { :ary =&gt; %w(one two three four) }&lt;br /&gt;&lt;br /&gt;# Define a method, 'use', for all objects&lt;br /&gt;# This version uses explicit passing&lt;br /&gt;class Object&lt;br /&gt;  def use &amp;amp;prc&lt;br /&gt;    prc.call self&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# This version uses implicit passing&lt;br /&gt;class Object&lt;br /&gt;  def use&lt;br /&gt;    yield self&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# invoke 'use' on a specific member of the data structure&lt;br /&gt;data[:ary][2].use do |x|&lt;br /&gt; # Do stuff with x, rather than data[:ary][2]&lt;br /&gt; p "The number is #{x}"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://blog.sidu.in/2007/11/ruby-blocks-gotchas.html"&gt;http://blog.sidu.in/2007/11/ruby-blocks-gotchas.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.programimi.com/2007/10/11/ruby-on-rails-code-blocks-and-iteration/"&gt;http://www.programimi.com/2007/10/11/ruby-on-rails-code-blocks-and-iteration/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5910551958830937999?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5910551958830937999/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5910551958830937999' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5910551958830937999'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5910551958830937999'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/03/ruby-blocks.html' title='Ruby blocks'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7406817824057241337</id><published>2009-02-20T21:23:00.008Z</published><updated>2010-04-14T14:43:25.115+01:00</updated><title type='text'>Moving to Rails 2.2.2</title><content type='html'>Having just made the move from 2.1.2 to 2.2.2, I hought I wold share some of the issues I came across. There was a bug in 2.1.2 which meant that the image_tag method appended a dot to the end of the image filename, which has been resolved, so that is a good start.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Partials&lt;/strong&gt;&lt;br /&gt;The way you use partials has been updated in Rails 2.2. While the changes are certainly an improvement, modifying code is not fun (I had about 50 changes to make; thank goodness functional testing will catch your mistakes).&lt;br /&gt;&lt;br /&gt;The basic change is that &lt;code&gt;render_partial&lt;/code&gt; and &lt;code&gt;render_partial_collection&lt;/code&gt; now accept a single hash, rather than a string indicating the file and the important variable, and can be accessed through the &lt;code&gt;render&lt;/code&gt; method (thanks to mcclelland for pointing that out). The hash should have the file mapped to the :partial key, and any variables you want in your partial go in a hash mapped to the :locals key (so immediately we can see this is an improvement; you can pass as many of these as you want). These are accessed like local variables in your partial (but really as method calls, I assume). Class variables can be accessed in your partial just as they can in normal views.&lt;br /&gt;&lt;br /&gt;To render a collection, just map it to :collection. You can also map any HTML code you want between the elements of your collection to the :spacer key. Rails works out that if :partial is present, it has to render a partial, and if :collection is present, it has to render that partial as a collection, so I would use &lt;code&gt;render&lt;/code&gt; for everything (and personally, I would have removed or made private &lt;code&gt;render_partial&lt;/code&gt; and &lt;code&gt;render_partial_collection&lt;/code&gt;  given that we all have to change our code anyway).&lt;br /&gt;&lt;br /&gt;Let us see how it has changed. In this first example, a single variable is passed, which I have called :list (so I do not have to change the partial itself):&lt;br /&gt;&lt;pre&gt;# Old version&lt;br /&gt;&amp;lt;%=  render_partial 'list', @events %&gt;&lt;br /&gt;&lt;br /&gt;# New version&lt;br /&gt;&amp;lt;%=  render :partial =&gt; 'list', :locals =&gt; { :list =&gt; @events } %&gt;&lt;/pre&gt;&lt;br /&gt;Here is a table that uses two partials. The first, for the headings, requires no variables. The second is passed an array mapped to :collection:&lt;br /&gt;&lt;pre&gt;# Old version&lt;br /&gt;&amp;lt;table width="100%"&gt;&lt;br /&gt;&amp;lt;%=  render_partial 'table_headings', nil %&gt;&lt;br /&gt;&amp;lt;%=  render_partial_collection 'table_row', @samples %&gt;&lt;br /&gt;&amp;lt;/table&gt;&lt;br /&gt;&lt;br /&gt;# New version&lt;br /&gt;&amp;lt;table width="100%"&gt;&lt;br /&gt;&amp;lt;%=  render :partial =&gt; 'table_headings' %&gt;&lt;br /&gt;&amp;lt;%=  render :partial =&gt; 'table_row', :collection =&gt; @samples %&gt;&lt;br /&gt;&amp;lt;/table&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Error pages&lt;/strong&gt;&lt;br /&gt;There are three error pages in the public directory, which Rails uses when something goes wrong in the production environment (rather than giving error details). I think these were passed through ERb previously. This is no longer the case.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;br /&gt;When running tests, if the system encounters an error, it just gives up, instead of noting the error, and moving on to the next test. I strongly suspect this is a bug.&lt;br /&gt;&lt;br /&gt;If a user tries to do something when logged in, but without the required role, he gets redirected to the root page. In the controller, I specify a controller and an action. Previously, I could specify that in the redirect too, but not now. It took some seaching to find that I needed this:&lt;br /&gt;&lt;pre&gt;assert_redirected_to "http://test.host/"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Another change in that Rails now generates tests in a different form:&lt;br /&gt;&lt;pre&gt;#Old format&lt;br /&gt;def test_my_method&lt;br /&gt;some_code&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;#New format&lt;br /&gt;test "my method" do&lt;br /&gt;some_code&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The old format still works - no need to change all your old tests. Rather than creating a whole new set of methods, you are now invoking the test method... which then defines a new method by prepending test_ to the name, and then doing exactly the same as it did previously.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Tomcat problem&lt;/strong&gt;&lt;br /&gt;Having got everything working fine in the development environment, and all tests passing, I was confident to move to the production environmemt...&lt;br /&gt;&lt;pre&gt;19-Feb-2009 14:40:58 org.apache.catalina.core.ApplicationContext log&lt;br /&gt;SEVERE: unable to create shared application instance&lt;br /&gt;org.jruby.rack.RackInitializationException: undefined method `cache_template_loading=' for ActionView::Base:Class&lt;br /&gt;...&lt;br /&gt;19-Feb-2009 11:23:00 org.apache.catalina.core.ApplicationContext log&lt;br /&gt;SEVERE: Exception caught&lt;br /&gt;java.lang.NullPointerException&lt;br /&gt;at org.jruby.rack.DefaultRackDispatcher.process(DefaultRackDispatcher.java:32)&lt;br /&gt;at org.jruby.rack.RackFilter.doFilter(RackFilter.java:51)&lt;/pre&gt;&lt;br /&gt;Oh dear. After much searching (and updating JRuby from 1.1.4 to 1.1.6), I found &lt;a href="http://railsforum.com/viewtopic.php?id=23648"&gt;this forum thread&lt;/a&gt;. The solution was to remove the following line from config/environment/production.rb (may also be in config/environment.rb):&lt;br /&gt;&lt;pre&gt;config.action_view.cache_template_loading = true&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;A has_one problem&lt;/strong&gt;&lt;br /&gt;An obscure bug I came across for the has_one/belongs_to relationship. When I attempted to access one model from the other, I got a &lt;code&gt;NoMethodError&lt;/code&gt; exception, and a complaint that I was tryong to do &lt;code&gt;nil.include?&lt;/code&gt;. My has_many/belongs_to relationships worked fine. The problem was related to setting the time zone. I have no idea how that can be, but I was not the only one:&lt;br /&gt;&lt;a href="http://www.nabble.com/Strange-error...-td21313953.html"&gt;http://www.nabble.com/Strange-error...-td21313953.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.railsformers.com/article/activerecord-timezone-settings-bug"&gt;http://www.railsformers.com/article/activerecord-timezone-settings-bug&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Anyway, the solution is to delete or comment out the old time zone configuration in config/environment.rb, and put in a new one.&lt;br /&gt;&lt;pre&gt;  #config.time_zone = 'UTC'&lt;br /&gt;config.active_record.default_timezone = :utc&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Additional: &lt;span style="font-style: italic;"&gt;Rails 2.3.2 has been out for a while, and I have tried using that. The only noticeable difference was application.rb was renamed to application_controller.rb. Right up until I tried to deploy on Tomcat and it all stopped working. There is a word around &lt;a href="http://kenai.com/projects/jruby/pages/Rails_2_3_2"&gt;here&lt;/a&gt;, but I have a suspicion this assumes you have created your project with a more recent version of Rails than I did. Anyway, it did not work for me, so I am back on 2.2.2.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Further addition: &lt;span style="font-style: italic;"&gt;Going back to 2.2.2 caused my unit tests to fail mysteriously, with rake just giving up (though functionals and integration tests were fine, and each unit test on its own was fine). It turned out that new models I had added with 2.3.2 had an additional test in test/units/helpers, and this was upsetting the rake task (possibly because I had deleted the associated helper files).&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7406817824057241337?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7406817824057241337/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7406817824057241337' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7406817824057241337'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7406817824057241337'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/02/moving-to-rails-222.html' title='Moving to Rails 2.2.2'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4928512163647579693</id><published>2009-02-13T00:01:00.005Z</published><updated>2010-02-23T10:48:17.103Z</updated><title type='text'>The Ruby Proc</title><content type='html'>In Ruby a &lt;code&gt;Proc&lt;/code&gt; (short for procedure) is a block of code, bound to a variable (closely related to a block, discussed &lt;a href="http://strugglingwithruby.blogspot.com/2009/03/ruby-blocks.html"&gt;here&lt;/a&gt;). As is always the way in Ruby, a &lt;code&gt;Proc&lt;/code&gt; is an object, and so can be created with the &lt;code&gt;new&lt;/code&gt; method, though, as discussed later, it is generally preferable to use the &lt;code&gt;lambda&lt;/code&gt; method. Here are some examples (expanding on those in the Ruby documention):&lt;br /&gt;&lt;pre&gt;# A Proc can have one, none or many arguments&lt;br /&gt;times7 = Proc.new {|n| n * 7 }&lt;br /&gt;statement = Proc.new { 'from statement' }&lt;br /&gt;multiply3 = Proc.new {|x, y| x * y }&lt;/pre&gt;&lt;br /&gt;The code in the Proc object can be invoked by using the call method.&lt;br /&gt;&lt;pre&gt;p times3.call(12)               #=&gt; 36&lt;br /&gt;p times5.call(5)                #=&gt; 25&lt;br /&gt;p times7.call(8)                #=&gt; 56&lt;br /&gt;p times3.call(times5.call(4))   #=&gt; 60&lt;br /&gt;&lt;br /&gt;p statement.call                #=&gt; "from statement"&lt;br /&gt;p multiply.call(4, 3)           #=&gt; 12&lt;/pre&gt;&lt;br /&gt;You can pass around Proc objects like any other object:&lt;br /&gt;&lt;pre&gt;def gen_times(factor)&lt;br /&gt; return Proc.new {|n| n*factor }&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class ProcTest&lt;br /&gt; # Class variable is a Proc&lt;br /&gt; @@times13 = Proc.new {|n| n * 13 }&lt;br /&gt;&lt;br /&gt; # Method uses various Proc objects&lt;br /&gt; def test&lt;br /&gt;   times11 = Proc.new {|n| n * 11 }&lt;br /&gt;   p times11.call(3)&lt;br /&gt;   p @@times13.call(7)&lt;br /&gt;   times2 = gen_times(2)&lt;br /&gt;   p times2.call(19)&lt;br /&gt; end&lt;br /&gt;&lt;br /&gt; # Method uses a Proc passed as an argument&lt;br /&gt; def test_argument prc&lt;br /&gt;   p prc.call(4)&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# ProcTest object instantiated, and methods called&lt;br /&gt;pt = ProcTest.new&lt;br /&gt;pt.test&lt;br /&gt;pt.test_argument Proc.new {|x| x + 5}&lt;/pre&gt;&lt;br /&gt;Instead of using call, you can invoke the code using square brackets notation. The following are equivalent:&lt;br /&gt;&lt;pre&gt;multiply.call(4, 3)&lt;br /&gt;multiply[4, 3]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Proc.new vs lambda&lt;/strong&gt;&lt;br /&gt;If you call a Proc with too few arguments, Ruby will pad them out with the nil object, so multiply.call(14) above would invoke the Proc code with 14 and nil (which would generate an error in this case). Any extra arguments are simply discarded.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;Kernal&lt;/code&gt; has a method &lt;code&gt;lambda&lt;/code&gt; (there is also a method &lt;code&gt;proc&lt;/code&gt;, which reportedly does the same as &lt;code&gt;Proc.new&lt;/code&gt;, but I found it identical to &lt;code&gt;lambda&lt;/code&gt;) which will also give a &lt;code&gt;Proc&lt;/code&gt; object, but in this case the &lt;code&gt;Proc&lt;/code&gt; will raise an &lt;code&gt;ArgumentError&lt;/code&gt; is the argument count is wrong.&lt;br /&gt;&lt;pre&gt;count_nils_new = Proc.new {|x, y, z|&lt;br /&gt;"#{x.nil?} #{y.nil?} #{z.nil?}"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;count_nils_lambda = lambda {|x, y, z|&lt;br /&gt;"#{x.nil?} #{y.nil?} #{z.nil?}"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;# The 4 is quietly discarded&lt;br /&gt;p count_nils_new.call(1, 2, 3, 4)&lt;br /&gt;&lt;br /&gt;# The method is sent 1, 2, nil&lt;br /&gt;p count_nils_new.call(1, 2)&lt;br /&gt;&lt;br /&gt;# The method is sent nil, nil, nil&lt;br /&gt;p count_nils_new.call&lt;br /&gt;&lt;br /&gt;# This is fine&lt;br /&gt;p count_nils_lambda.call(1, 2, 3)&lt;br /&gt;&lt;br /&gt;# These will all generate an ArgumentError&lt;br /&gt;p count_nils_lambda.call(1, 2, 3, 4)&lt;br /&gt;p count_nils_lambda.call(1, 2)&lt;br /&gt;p count_nils_lambda.call&lt;/pre&gt;&lt;br /&gt;&lt;code&gt;Proc&lt;/code&gt; objects have an &lt;code&gt;arity&lt;/code&gt; method that can be used to determine how many arguments the &lt;code&gt;Proc&lt;/code&gt; is expecting.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using return in a Proc&lt;/strong&gt;&lt;br /&gt;Using an explicit &lt;code&gt;return&lt;/code&gt; in a &lt;code&gt;Proc&lt;/code&gt; object created with &lt;code&gt;Proc.new&lt;/code&gt; (but not &lt;code&gt;lambda&lt;/code&gt;) will cause the calling method to return that value.&lt;br /&gt;&lt;pre&gt;def with_return_and_new&lt;br /&gt;prc = Proc.new { return 'This is printed' }&lt;br /&gt;prc.call&lt;br /&gt;'Never seen'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def no_return_with_new&lt;br /&gt;prc = Proc.new { 'no_return_with_new' }&lt;br /&gt;prc.call&lt;br /&gt;'This is printed'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def with_return_and_lambda&lt;br /&gt;prc = lambda { return 'with_return_and_lambda' }&lt;br /&gt;prc.call&lt;br /&gt;'This is printed'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;p with_return_and_new&lt;br /&gt;p no_return_with_new&lt;br /&gt;p with_return_and_lambda&lt;/pre&gt;&lt;br /&gt;It seems that the &lt;code&gt;Proc&lt;/code&gt; object is returning not just the value, but the &lt;code&gt;return&lt;/code&gt; command too. In general, therefore, it is a bad idea to use an explicit &lt;code&gt;return&lt;/code&gt; inside a &lt;code&gt;Proc&lt;/code&gt; object defined with &lt;code&gt;Proc.new&lt;/code&gt; (if only because the effect will be confusing to anyone with out a good understanding of Ruby peculiarities). This is discussed more here:&lt;br /&gt;&lt;a href="http://innig.net/software/ruby/closures-in-ruby.rb"&gt;http://innig.net/software/ruby/closures-in-ruby.rb&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;API for the Proc object:&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/Proc.html"&gt;http://www.ruby-doc.org/core/classes/Proc.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/"&gt;http://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods/&lt;/a&gt;&lt;br /&gt;&lt;a href="http://blog.sidu.in/2007/11/ruby-blocks-gotchas.html"&gt;http://blog.sidu.in/2007/11/ruby-blocks-gotchas.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4928512163647579693?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4928512163647579693/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4928512163647579693' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4928512163647579693'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4928512163647579693'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/02/ruby-proc.html' title='The Ruby Proc'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-8094109513202143610</id><published>2009-02-08T12:46:00.004Z</published><updated>2009-04-01T10:45:27.559+01:00</updated><title type='text'>The Singleton in Ruby</title><content type='html'>When I first read about singletons in Ruby, I assumed this was a reference to the &lt;a href="http://en.wikipedia.org/wiki/Singleton_pattern"&gt;singleton pattern&lt;/a&gt;; perhaps &lt;i&gt;the&lt;/i&gt; classic example of a pattern, and in my opinion not much use (actually Ruby has a &lt;a href="http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html"&gt;&lt;code&gt;Singleton&lt;/code&gt;&lt;/a&gt; module for doing just this). However, in Ruby the singleton is something else entirely.&lt;br /&gt;&lt;br /&gt;The singleton is a method that is attached to a single instance of a class. Here is a simple example:&lt;br /&gt;&lt;pre&gt;s1 = 'what'&lt;br /&gt;s2 = 'where'&lt;br /&gt;s3 = 'when'&lt;br /&gt;&lt;br /&gt;def s1.hello&lt;br /&gt; p "Hello world"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class &amp;lt;&amp;lt; s2&lt;br /&gt;  def hello&lt;br /&gt;    p "Hello world"&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;s1.hello&lt;br /&gt;s2.hello&lt;br /&gt;begin&lt;br /&gt;  s3.hello&lt;br /&gt;rescue NoMethodError&lt;br /&gt;  p $!&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;p s1.singleton_methods&lt;br /&gt;    # =&gt; ["hello"]&lt;br /&gt;p s2.singleton_methods&lt;br /&gt;   # =&gt; ["hello"]&lt;br /&gt;p s3.singleton_methods&lt;br /&gt;   # =&gt; []&lt;/pre&gt;&lt;br /&gt;Three strings are created. The first two have singleton methods added to them in slightly different ways. The singleton methods can be invoked on that specific instance, but not on any other object of that class. Finally, the &lt;code&gt;singleton_methods&lt;/code&gt; method is invoked to show how these methods can be listed.&lt;br /&gt;&lt;br /&gt;Technically, the object itself does not get a new method. Objects can only hold variables, not methods. Rather, the object has a metaclass, or virtual class, and this metaclass is where the new method is. This is what &lt;code&gt;class &amp;lt;&amp;lt; s2&lt;/code&gt; is accessing.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Class methods&lt;/strong&gt;&lt;br /&gt;You can also add singleton methods to the class, where they become class methods. The logic here is that the class is itself an object, and these methods are being added to a single instance of the &lt;code&gt;Class&lt;/code&gt; class. This code illustrates three ways to add a singleton to a class.&lt;br /&gt;&lt;pre&gt;def String.goodbye1&lt;br /&gt; p "Goodbye world (1)"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class String&lt;br /&gt; def self.goodbye2&lt;br /&gt;   p "Goodbye world (2)"&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class String&lt;br /&gt; class &amp;lt;&amp;lt; self&lt;br /&gt;  def goodbye3&lt;br /&gt;   p "Goodbye world (3)"&lt;br /&gt;  end&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;p String.singleton_methods&lt;br /&gt;# =&gt; ["goodbye3", "goodbye2", "goodbye1"]&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It is interesting to note that "String" is actually a constant that holds a &lt;code&gt;Class&lt;/code&gt; object, and this is why it is capitalised.&lt;br /&gt;&lt;br /&gt;Note: &lt;a href="http://ozmm.org/posts/class__self_is_harmful.html"&gt;Some&lt;/a&gt; believe that &lt;code&gt;class &amp;lt;&amp;lt; self&lt;/code&gt; is bad; this suggests there may be more going on here.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;singleton_methods&lt;/code&gt; method returns all methods for the class that are not inherited from a superclass. Use &lt;code&gt;singleton_methods false&lt;/code&gt; to exclude methods from modules.&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html"&gt;http://ola-bini.blogspot.com/2006/09/ruby-singleton-class.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html"&gt;http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-8094109513202143610?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/8094109513202143610/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=8094109513202143610' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8094109513202143610'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8094109513202143610'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/02/singleton-in-ruby.html' title='The Singleton in Ruby'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7846529291566820304</id><published>2009-02-03T21:15:00.003Z</published><updated>2009-02-05T10:49:45.050Z</updated><title type='text'>Modules</title><content type='html'>A module is a collection of methods and constants, much like a method. However, a module cannot be instantiated. Instead, a module is added to an existing class or object to create a "mixin". Here is an example of a module, with both a method and a constant defined:&lt;br /&gt;&lt;pre&gt;module TestModule&lt;br /&gt;TEST_CONST = 1000&lt;br /&gt;&lt;br /&gt;def hello&lt;br /&gt;  p "Hello"&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The are two ways to add a module to your class, using the keywords &lt;code&gt;include&lt;/code&gt; or &lt;code&gt;extend&lt;/code&gt;:&lt;br /&gt;&lt;pre&gt;class TestClass1&lt;br /&gt;include TestModule&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class TestClass2&lt;br /&gt;extend TestModule&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;include&lt;/code&gt; statement causes all the methods in the module to be added as instance methods, and also allows the constants to be accessed through the method. In contrast, the &lt;code&gt;extend&lt;/code&gt; statement adds all the methods as class methods, and does nothing with the constants. Let us look at the constants first:&lt;br /&gt;&lt;pre&gt;p TestModule::TEST_CONST&lt;br /&gt;p TestClass1::TEST_CONST&lt;br /&gt;begin&lt;br /&gt;p TestClass2::TEST_CONST&lt;br /&gt;rescue NameError&lt;br /&gt;p $!&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The class methods. TestClass2 had the module added using &lt;code&gt;extend&lt;/code&gt;, so the method in the module is a class method:&lt;br /&gt;&lt;pre&gt;begin&lt;br /&gt;TestClass1.hello&lt;br /&gt;rescue NoMethodError&lt;br /&gt;p $!&lt;br /&gt;end&lt;br /&gt;TestClass2.hello&lt;/pre&gt;&lt;br /&gt;Finally the instance methods. TestClass1 had the module added using &lt;code&gt;include&lt;/code&gt;, so the method in the module is an instance method. Note that you can add a module to an object at run time, but in that case the &lt;code&gt;extend&lt;/code&gt; keyword is used:&lt;br /&gt;&lt;pre&gt;# Create some instances&lt;br /&gt;tc1 = TestClass1.new&lt;br /&gt;tc2 = TestClass2.new&lt;br /&gt;tc2too = TestClass2.new&lt;br /&gt;&lt;br /&gt;# Methods accessible at the instance level&lt;br /&gt;tc1.hello&lt;br /&gt;begin&lt;br /&gt;tc2.hello&lt;br /&gt;rescue NoMethodError&lt;br /&gt;p $!&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Module added at runtime&lt;br /&gt;tc2.extend TestModule&lt;br /&gt;tc2.hello&lt;br /&gt;begin&lt;br /&gt;tc2too.hello&lt;br /&gt;rescue NoMethodError&lt;br /&gt;p $!&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I think the logic here is that &lt;code&gt;extend&lt;/code&gt; is used for singletons; a single class or a single instance of the class.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Instantiation&lt;/strong&gt;&lt;br /&gt;Ruby will invoke the included or extended methods in your module, if they exist, when the module is included or extended respectively. These have to be defined as class methods - even though this is not a class. As far as I know, this is the only time you do tat for a module. Both methods should take a single parameter; the object or class to which the module is being added. An example:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;module TestModule&lt;br /&gt;def self.included base&lt;br /&gt;  p "I am being included by #{base}"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.extended base&lt;br /&gt;  p "I am being extended by #{base}"&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class TestClass1&lt;br /&gt;include TestModule&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class TestClass2&lt;br /&gt;extend TestModule&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;p 'Classes now defined'&lt;br /&gt;&lt;br /&gt;tc2 = TestClass2.new&lt;br /&gt;tc2.extend TestModule&lt;br /&gt;&lt;br /&gt;# Output&lt;br /&gt;#&lt;br /&gt;# =&gt; "I am being included by TestClass1"&lt;br /&gt;# =&gt; "I am being extended by TestClass2"&lt;br /&gt;# =&gt; "Classes now defined"&lt;br /&gt;# =&gt; "I am being extended by #&amp;lt;TestClass2:0x987a33&gt;"&lt;/pre&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/"&gt;http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7846529291566820304?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7846529291566820304/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7846529291566820304' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7846529291566820304'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7846529291566820304'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/02/modules.html' title='Modules'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7805354922497552582</id><published>2009-01-24T19:36:00.005Z</published><updated>2010-01-06T09:24:26.937Z</updated><title type='text'>The View Part 4 - Using Select in Forms</title><content type='html'>Last time around, I discussed forms, I am now going to focus on the select widget, as I found this particular mysterious at first. I am going to assume you have already read the page on forms.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using f.select&lt;/strong&gt;&lt;br /&gt;The easiest way to use select is inside a &lt;code&gt;FormBuilder&lt;/code&gt; block. While most &lt;code&gt;FormBuilder&lt;/code&gt; code is in &lt;code&gt;form_helper.rb&lt;/code&gt;, the select is in &lt;code&gt;form_options_helper&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Suppose you have a column for integers in your database table (let us say "status", for example, in a table called "posts"). You want the user to be able to select an option from a drop-down list to set the value of the column. First, you need a set of options, and this is best defined in your model. This could be an array or a hash. If you use a hash, you can assign values to options yourself, but generally an array will be sufficient. I am going to use a hash, so in posts.rb, there will be this constant defined:&lt;br /&gt;&lt;pre&gt;STATUS_OPTIONS = {'Read' =&gt; 1, 'Unread' =&gt; 2, 'Deleted' =&gt; 12}&lt;/pre&gt;&lt;br /&gt;Then, in the view, you just need a &lt;code&gt;f.select&lt;/code&gt;. It might look something like this (with other fields removed for clarity):&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_for(@post) do |f| %&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;Please select:&lt;br /&gt;&amp;lt;%= f.select(:status, Post::STATUS_OPTIONS) %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;&amp;lt;%= f.submit "Update" %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;f.select&lt;/code&gt; takes two parameters, the first being the name of the column (or any method as a symbol), the second is the array or hash. That is all you need to do. Rails will handle the saving and setting of the options for you.&lt;br /&gt;&lt;br /&gt;Be aware that if you use an array, Rails will ignore the index. The value returned from the column method must be a value in the array, rather than a number for the index, and similarly what is set will be value, not the index. Personally, I found that annoying, so created a new method that would accept an array, and build a select element using the indices with the values.&lt;br /&gt;&lt;pre&gt;# See actionpack/lib/action_view/helpers/form_options_helper.rb&lt;br /&gt;module ActionView&lt;br /&gt; module Helpers&lt;br /&gt;   class FormBuilder&lt;br /&gt;     def array_select(method, choices, options = {}, html_options = {})&lt;br /&gt;       h = {}&lt;br /&gt;       choices.each_index { |i| h.store(choices[i], i)}&lt;br /&gt;       @template.select(@object_name, method, h, objectify_options(options), @default_options.merge(html_options))&lt;br /&gt;     end&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using select_tag&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;select_tag&lt;/code&gt; method is a bit poor, as it does not accept an array or hash, demanding instead a string with each entry surrounded by "&amp;lt;option&gt;" and "&amp;lt;/option&gt;". Why it was not designed to accept an array and a value I cannot imagine. Instead, you have to use the &lt;code&gt;options_for_select&lt;/code&gt; helper method, like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= select_tag("post[status]",&lt;br /&gt;options_for_select(Post::STATUS_OPTIONS,&lt;br /&gt;                  @post.status))&lt;br /&gt;%&gt;&lt;/pre&gt;&lt;br /&gt;However, there is also a select method that does the job.&lt;br /&gt;&lt;pre&gt;&amp;lt;%= select(:post, :status, Post::STATUS_OPTIONS) %&gt;&lt;/pre&gt;&lt;br /&gt;I imagine this was a later addition to Rails.&lt;br /&gt;&lt;br /&gt;NOTE: I have read that select_tag should be used for GET commands, and select for POST (see &lt;a href="http://shiningthrough.co.uk/blog/show/7"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Submit on change to a select&lt;/strong&gt;&lt;br /&gt;Sometimes, you want the user to be able to select from a list, and to be taken straight to a new web page, without having to click on a button. This is pretty easy, with a bit of JavaScript. I set up a helper method to do that:&lt;br /&gt;&lt;pre&gt;def submit_on_change&lt;br /&gt;{:onchange =&gt; 'submit()'}&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can then add that method to your &lt;code&gt;select&lt;/code&gt; or &lt;code&gt;select_tag&lt;/code&gt;. Note that &lt;code&gt;select&lt;/code&gt; takes two optional hashes, and you want to use the second, so I have put in an empty hash in that case.&lt;br /&gt;&lt;pre&gt;&amp;lt;%= f.select :status, Post::STATUS_OPTIONS, {}, submit_on_change %&gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;%= select_tag "post[status]",&lt;br /&gt; options_for_select(Post::STATUS_OPTIONS,&lt;br /&gt;        @post.status),&lt;br /&gt; submit_on_change %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Another select example&lt;/strong&gt;&lt;br /&gt;Here is an example of using a select box to choose a web page. The web pages are set up in the model:&lt;br /&gt;&lt;pre&gt;HELP_PAGES = {'Main' =&gt; 'index', 'Ruby Basics' =&gt; 'ruby', 'Ruby Classes' =&gt; 'classes'}&lt;/pre&gt;&lt;br /&gt;In the view, this code will set up the select (note that there is no submit button; be aware that any user with JavaScript disabled will not be able to navigate using this):&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag( {:action =&gt; :help, }, :method =&gt; :get) do %&gt;&lt;br /&gt;&amp;lt;%= select_tag "page", options_for_select(Post::HELP_PAGES),&lt;br /&gt;             submit_on_change %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;In the controller, the chosen page is handled:&lt;br /&gt;&lt;pre&gt;def help&lt;br /&gt;@page = params[:page]&lt;br /&gt;# etc...&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The collection_select method&lt;/strong&gt;&lt;br /&gt;Let us suppose you have one table associated with another, and want to be able to have the user select a record from one table for a record in the other. Let us go back to the archetypal blog application: Posts can be associated with a category (so a post &lt;code&gt;belongs_to&lt;/code&gt; a category; a category &lt;code&gt;has_many&lt;/code&gt; posts and the post table has a column called "category_id"). The user clicks on &lt;code&gt;new post&lt;/code&gt;, writes his throughts, then can select from a list of categories from a drop-down list. How do we create such a thing?&lt;br /&gt;&lt;br /&gt;This is what the &lt;code&gt;collection_select&lt;/code&gt; method is for. As with &lt;code&gt;select&lt;/code&gt;, there are two forms, one associated with a &lt;code&gt;FormBuilder&lt;/code&gt; object, the other not.&lt;br /&gt;&lt;pre&gt;&amp;lt;%= f.collection_select(:category_id,&lt;br /&gt;     Category.find(:all), :id, :name) %&gt;&lt;br /&gt;&amp;lt;%= collection_select(:post, :category_id,&lt;br /&gt; Category.find(:all), :id, :name) %&gt;&lt;/pre&gt;&lt;br /&gt;Note that the second form requires an extra parameter specifying the table we are modifying. The next parameter, :category_id in the example, is a method that is called to set the value; generally that will be the name of the column in the table you are modifying.&lt;br /&gt;&lt;br /&gt;The next parameter is an array (kind of) of &lt;code&gt;ActiveRecord&lt;/code&gt;s; this is the list of options that will be available to the user. The next parameter, :id, is the method used by Rails to get values for each option of the select, while the next parameter determines the display name for the options. In effect, these two are the column names in the other table. To generate the list of options in the example, Rails iterates through the array of categories, and for each member it calls the "id" method to set the value, and the "name" method to set the text that is displayed.&lt;br /&gt;&lt;br /&gt;As with &lt;code&gt;select&lt;/code&gt;, there are two optional parameters for hashes of options.&lt;br /&gt;&lt;br /&gt;As it turns out, you are not restricted to &lt;code&gt;ActiveRecord&lt;/code&gt;s. I tried it with this TestClass:&lt;br /&gt;&lt;pre&gt;class TestClass&lt;br /&gt;def initialize id, name&lt;br /&gt;@id = id&lt;br /&gt;@name = name&lt;br /&gt;end&lt;br /&gt;attr_reader :id, :name&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Setting up an array:&lt;br /&gt;&lt;pre&gt;  TEST_ARRAY = [&lt;br /&gt;TestClass.new(12, 'First of all'),&lt;br /&gt;TestClass.new(54, 'Middle'),&lt;br /&gt;TestClass.new(32, 'Last and finally'),&lt;br /&gt;]&lt;/pre&gt;&lt;br /&gt;And then using the &lt;code&gt;collection_select&lt;/code&gt; like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= collection_select(:comment, :post_id,&lt;br /&gt;      Comment::TEST_ARRAY, :id, :name) %&gt;&lt;/pre&gt;&lt;br /&gt;However, I have no idea why you would want to do that, rather than using a hash with &lt;code&gt;select&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Selecting Dates&lt;/strong&gt;&lt;br /&gt;There are are set of methods to help you handle dates. If you are inside a &lt;code&gt;FormBuilder&lt;/code&gt; block, just use &lt;code&gt;date_select&lt;/code&gt; like this (Rails will even do this for you when you generate views):&lt;br /&gt;&lt;%= f.date_select :birthday %&gt;&lt;br /&gt;&lt;code&gt;ActiveRecord&lt;/code&gt; will handle the rest. Outside &lt;code&gt;FormBuilder&lt;/code&gt; you can use &lt;code&gt;date_select&lt;/code&gt; or &lt;code&gt;select_date&lt;/code&gt; (why not &lt;code&gt;date_select_tag&lt;/code&gt;, which would be more consistent?). I found &lt;code&gt;date_select&lt;/code&gt; easier to set up, but the values in the hash are not trivial to handle. I found some useful code &lt;a href="http://blog.zerosum.org/2007/5/9/deconstructing-date_select"&gt;here&lt;/a&gt;:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;# Reconstruct a date object from date_select helper form params&lt;br /&gt;def build_date_from_params(field_name, params)&lt;br /&gt;Date.new(params["#{field_name.to_s}(1i)"].to_i,&lt;br /&gt;     params["#{field_name.to_s}(2i)"].to_i,&lt;br /&gt;     params["#{field_name.to_s}(3i)"].to_i)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;date = build_date_from_params(:published_at, params[:article])&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The API:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html"&gt;http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html"&gt;http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html"&gt;http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://shiningthrough.co.uk/Select+helper+methods+in+Ruby+on+Rails"&gt;http://shiningthrough.co.uk/Select+helper+methods+in+Ruby+on+Rails&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7805354922497552582?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7805354922497552582/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7805354922497552582' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7805354922497552582'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7805354922497552582'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/01/viw-part-4-using-select-in-forms.html' title='The View Part 4 - Using Select in Forms'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-9165301668206732804</id><published>2009-01-23T22:12:00.003Z</published><updated>2009-02-24T10:56:26.039Z</updated><title type='text'>The View Part 3 - Using Forms</title><content type='html'>The basic component of a form for a view on Rails is the &lt;code&gt;form_for&lt;/code&gt; method in &lt;code&gt;ActionView::Helpers::FormHelper&lt;/code&gt;. This takes an object as an argument, and applies that object to the form components in a block. The variabe &lt;code&gt;f&lt;/code&gt; is a &lt;code&gt;FormBuilder&lt;/code&gt; object.&lt;br /&gt;&lt;pre&gt;form_for(@post) do |f|&lt;br /&gt;f.label :name&lt;br /&gt;f.text_field :name&lt;br /&gt;f.label :body&lt;br /&gt;f.text_area :body&lt;br /&gt;f.submit "Update"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Actually, it is not quite as simple as that, as you need to mix in the HTML, so in your view, the above becomes:&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_for(@post) do |f| %&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;  &amp;lt;%= f.label :name %&gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;%= f.text_field :name %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;  &amp;lt;%= f.label :body %&gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;%= f.text_area :body %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;  &amp;lt;%= f.submit "Update" %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;It is a good idea to put in &lt;code&gt;&amp;lt;%= f.error_messages %&gt;&lt;/code&gt; as the second line in your form (and indeed Rails will do this for you), as this will display error messages for you (for example, if the user's input fails validation).&lt;br /&gt;&lt;br /&gt;There are a number of methods available for the &lt;code&gt;FormHelper&lt;/code&gt; object that will place widgets on the web page. These ones are listed in the API:&lt;br /&gt;&lt;pre&gt;check_box&lt;br /&gt;file_field&lt;br /&gt;hidden_field&lt;br /&gt;label&lt;br /&gt;password_field&lt;br /&gt;radio_button&lt;br /&gt;text_area&lt;br /&gt;text_field&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;check_box&lt;/code&gt; method should be associated with a Boolean field. The &lt;code&gt;hidden_field&lt;/code&gt; is useful for data you do not want the user to have access to, but which has to saved with the rest of the fields (but if a field is missing from the form, the record will retain the previous value).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using radio_button&lt;/strong&gt;&lt;br /&gt;Suppose you have a column for integers in your database table (let us say "status", for example, in a table called "posts"). You want the user to be able to select an option.&lt;br /&gt;&lt;br /&gt;First, you need a set of options, and this is best defined in your model. I am going to use a hash, so in posts.rb, there will be this constant defined:&lt;br /&gt;&lt;pre&gt;STATUS_OPTIONS = {'Read' =&gt; 1, 'Unread' =&gt; 2, 'Deleted' =&gt; 12}&lt;/pre&gt;&lt;br /&gt;Then, in the view, you just need something like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;% Post::STATUS_OPTIONS.each_pair do |k, v| %&gt;&lt;br /&gt;&amp;lt;%= k + f.radio_button("status", v) %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;Ruby will iterate through the hash, &lt;code&gt;Post::STATUS_OPTIONS&lt;/code&gt;. For each element, it will create a radio button.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Buttons that do not submit&lt;/strong&gt;&lt;br /&gt;Sometimes you want a button that does not submit the form. You can still use the submit method, just set the :type to map to "button. Here is an example of how to create a button that will invoke a JavaScript function called calc.&lt;br /&gt;&lt;pre&gt;&amp;lt;%= f.submit 'Calc', { :onclick =&gt; 'calc()', :type =&gt; "button", } %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Other Forms&lt;/strong&gt;&lt;br /&gt;Sometimes you want to create a form that is not associated with a particular record, such as a search form. For this you use methods from the &lt;code&gt;ActionView::Helpers::FormTagHelper&lt;/code&gt; module. The same sort of methods are available, but with &lt;code&gt;_tag&lt;/code&gt; as a suffix.&lt;br /&gt;&lt;br /&gt;Use &lt;code&gt;form_tag&lt;/code&gt; to create the basic form. You can give it a URL segment, or the usual URL parameters. The &lt;code&gt;form_tag&lt;/code&gt; method seems to default to POST, so for this show example, I had to specify the method as GET.&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag({:action =&gt; :show, :id =&gt; 1}, :method =&gt; :get) do %&gt;&lt;br /&gt;&amp;lt;%= submit_tag 'Show 1' %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;Or using the URL:&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag '/posts/update/1' do %&gt;&lt;br /&gt;&amp;lt;%= submit_tag 'Update 1' %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;Here is a more interesting example, doing the same as the first example (just for illustration - there is no good reason to not do it the other way), with radio buttons. Note that the method is now PUT for update. Also, the tag name is of the form &lt;code&gt;post[status]&lt;/code&gt; (for the model called "post", and the field called "status"). When Rails receives the request, the value of status will be put in a hash called post, which will go inside the params hash. This is the standard Rails technique, and is what happens in the earlier example, behind the scenes. This means the controller does not need changing.&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_tag({:action =&gt; :update, :id =&gt; @post.id},&lt;br /&gt;           :method =&gt; :put) do %&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;  &amp;lt;%= label_tag 'Name' %&gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;%= text_field_tag 'post[name]', @post.name %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;p&gt;&lt;br /&gt;  &amp;lt;%= label_tag 'Body' %&gt;&lt;br /&gt;&lt;br /&gt;  &amp;lt;%= text_area_tag 'post[body]', @post.body %&gt;&lt;br /&gt;&amp;lt;/p&gt;&lt;br /&gt;&amp;lt;% i = 0&lt;br /&gt;  Post::STATUS_OPTIONS.each_pair do |k, v| %&gt;&lt;br /&gt;  &amp;lt;%= k + radio_button_tag('post[status]', v,&lt;br /&gt;            @post.status == v) %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;br /&gt;&amp;lt;%= submit_tag "Update" %&gt;&lt;br /&gt;&amp;lt;% end %&gt;&lt;/pre&gt;&lt;br /&gt;Hopefully tomorrow I will post about &lt;code&gt;select&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;The API:&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html"&gt;http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html"&gt;http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-9165301668206732804?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/9165301668206732804/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=9165301668206732804' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9165301668206732804'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9165301668206732804'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/01/view-part-2-using-forms.html' title='The View Part 3 - Using Forms'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5916876343845422031</id><published>2009-01-21T21:11:00.004Z</published><updated>2009-02-03T16:22:36.777Z</updated><title type='text'>Ruby Methods Part 4 - Calling Methods</title><content type='html'>Ruby has three (at least) ways to call a method on an object. This code illustrates their use. First, a class is defined with four methods, one of which is private, one is a class method and another takes a parameter. The class is instantiated, and then the methods accessed using the various techniques.&lt;br /&gt;&lt;pre&gt;# Define a class with three methods&lt;br /&gt;class MethodTest&lt;br /&gt;def public_method&lt;br /&gt; p 'In public_method'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def method_with_argument x&lt;br /&gt; p "In public2_method - #{x}"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.class_method&lt;br /&gt; p 'In class_method'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;private&lt;br /&gt;def private_method&lt;br /&gt; p 'In private_method'&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Create instance of class&lt;br /&gt;mt = MethodTest.new&lt;br /&gt;&lt;br /&gt;# Invoke methods with the dot operator&lt;br /&gt;mt.public_method&lt;br /&gt;mt.method_with_argument('hello')&lt;br /&gt;MethodTest.class_method&lt;br /&gt;begin&lt;br /&gt;mt.private_method&lt;br /&gt;rescue NoMethodError&lt;br /&gt;p $!&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# Invoke methods with send&lt;br /&gt;mt.send :public_method&lt;br /&gt;mt.send :method_with_argument, 'Hello'&lt;br /&gt;MethodTest.send :class_method&lt;br /&gt;mt.send :private_method&lt;br /&gt;&lt;br /&gt;# Invoke methods as objects&lt;br /&gt;mt.method(:public_method).call&lt;br /&gt;mt.method(:method_with_argument).call 'Hello'&lt;br /&gt;MethodTest.method(:class_method).call&lt;br /&gt;mt.method(:private_method).call&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;The dot operator&lt;/strong&gt;&lt;br /&gt;I guess this is the most familiar technique, and is common to other languages, like Java and C++. Private methods are not accessible, and instead a &lt;code&gt;NoMethodError&lt;/code&gt; is raised (and a message is produced informing you that the method is private).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The send method&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;send&lt;/code&gt; method is a part of the &lt;code&gt;Object&lt;/code&gt; class and so is available to all objects. It invokes the named method (must be a symbol). As the named method is now being invoked from within the object, this means that all the methods are available, including private and protected methods.&lt;br /&gt;&lt;br /&gt;Note that you can also use &lt;code&gt;__send__&lt;/code&gt;, in case you have overwritten the &lt;code&gt;send&lt;/code&gt; method. Overwriting &lt;code&gt;__send__&lt;/code&gt; will generate a warning that it is a &lt;i&gt;bad&lt;/i&gt; idea; Rails uses &lt;code&gt;__send__&lt;/code&gt; a lot, for example, on the assumption that no one would be stupid enough to over-write it.&lt;br /&gt;&lt;br /&gt;A good example of using the &lt;code&gt;send&lt;/code&gt; method is where you want to access database columns in a large table, where the columns are numbered sequentially, say column0, column1, column2, etc. Rails will handle the generation of methods that will allow &lt;code&gt;@mytable.column1 = 5 and x = @mytable.column1&lt;/code&gt;, but how do you get the total of the columns? Let us suppose ten such columns.&lt;br /&gt;&lt;pre&gt;total = 0&lt;br /&gt;10.times {|i|&lt;br /&gt;total += send("column" + i.to_s)&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Strangely, Ruby is quite a stickler for types. In Java or C# you could write &lt;code&gt;"column" + i&lt;/code&gt;, but Ruby requires the &lt;code&gt;to_s&lt;/code&gt; method to explicitly convert to a string. The &lt;code&gt;send&lt;/code&gt; method sends a message (in OO talk) to the named method, column0, column1, etc. To assign a value, you need to append an equals sign to the method name. This loop assigns zero to each column:&lt;br /&gt;&lt;pre&gt;10.times {i&lt;br /&gt;send("column" + i.to_s + "=", 0)&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;The &lt;code&gt;send&lt;/code&gt; method is a variable length method; just send it the right number of parameters for the method you are invoking.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The method object&lt;/strong&gt;&lt;br /&gt;Everything in Ruby is an object, including methods. You can access the method object with &lt;code&gt;my_object.method(:my_method)&lt;/code&gt;. Here is an example of using the method object for the length method of string&lt;br /&gt;&lt;pre&gt;s = "string"&lt;br /&gt;puts s.method(:length).class   # =&gt; Method&lt;br /&gt;puts s.method(:length).call  # =&gt; 6&lt;br /&gt;puts s.method(:length).methods.sort&lt;br /&gt;&lt;br /&gt;# =&gt; ["==", "===", "=~", "[]", "__id__", "__send__", ...&lt;/pre&gt;&lt;br /&gt;As seen earlier, the method that the object represents can be invoked using the &lt;code&gt;call&lt;/code&gt; method. As with &lt;code&gt;send&lt;/code&gt;, this allows you to access private and protected methods. By the way, you can convert a method to a &lt;code&gt;Proc&lt;/code&gt; using the &lt;code&gt;to_proc&lt;/code&gt; method.&lt;br /&gt;&lt;br /&gt;One important practical difference between using &lt;code&gt;send&lt;/code&gt; and using the &lt;code&gt;Method&lt;/code&gt; object is that the latter will only work on methods that are actually defined. It will not work for method calls that go though &lt;code&gt;method_missing&lt;/code&gt;, including calls to column names for &lt;code&gt;ActiveRecord&lt;/code&gt; or calls to the various find methods in Rails. This is because the method has to be defined to become an object.&lt;br /&gt;&lt;br /&gt;API for the &lt;code&gt;Method&lt;/code&gt; object:&lt;br /&gt;http://www.ruby-doc.org/core/classes/Method.html&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5916876343845422031?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5916876343845422031/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5916876343845422031' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5916876343845422031'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5916876343845422031'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/01/ruby-methods-part-4-calling-methods.html' title='Ruby Methods Part 4 - Calling Methods'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7642223589479513136</id><published>2009-01-09T22:58:00.003Z</published><updated>2009-01-19T12:00:49.274Z</updated><title type='text'>Rails Mailer</title><content type='html'>Rails includes a mailer facility. To use it, you need a model - a class that inherits from &lt;code&gt;ActionMailer::Base&lt;/code&gt; - and the best way to do that is use Rails to generate it:&lt;br /&gt;&lt;pre&gt;ruby script/generate mailer MyMailer send_book&lt;/pre&gt;&lt;br /&gt;This also creates some default views (in this case just one, send_book) and tests, but we will discuss that later. Let us suppose we want to send an e-mail with a record from a table called books. In a moment, we will set up a method called send_book in &lt;code&gt;MyMailer&lt;/code&gt;, but first, let us look at how we will invoke the mailer. In &lt;code&gt;books_controller&lt;/code&gt;, to send the mail, you need to invoke a class method that starts &lt;code&gt;deliver_&lt;/code&gt;.&lt;br /&gt;&lt;pre&gt;MyMailer.deliver_send_book(:user =&gt; current_user, :data =&gt; find_book)&lt;/pre&gt;&lt;br /&gt;Somewhere in &lt;code&gt;ActionMailer::Base&lt;/code&gt;, there is a &lt;code&gt;method_missing&lt;/code&gt; method that handles your request. It creates an instance of &lt;code&gt;MyMailer&lt;/code&gt;, does some setting up that we do not have to worry about, then invokes the method &lt;code&gt;send_book&lt;/code&gt;. This is where we assign values specific to this e-mail. It might look like this:&lt;br /&gt;&lt;pre&gt;def send_book(options)&lt;br /&gt;@recipients  = "#{options[:user].email}"&lt;br /&gt;@from        = "book-database@mydomain.com"&lt;br /&gt;@subject     = "Record from book database"&lt;br /&gt;@sent_on     = Time.now&lt;br /&gt;@content_type = 'text/html'&lt;br /&gt;@body[:user] = options[:user]&lt;br /&gt;@body[:book]  = options[:data]&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Note that this will send the message in HTML format; it will default to plain text if there is no &lt;code&gt;@content_type&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;Next the &lt;code&gt;method_missing&lt;/code&gt; method creates the text of the e-mail. It does this in the normal Rails manner, i.e., from a file in the views folder. In this case it will use &lt;code&gt;views/my_mail/send_book.html.erb&lt;/code&gt;. When you create &lt;code&gt;views/my_mail/send_book.erb&lt;/code&gt;, you have access to any variable you assign to the &lt;code&gt;@body&lt;/code&gt; hash, so in the example above, I could use &lt;code&gt;@user&lt;/code&gt; and &lt;code&gt;@book&lt;/code&gt;, just as in a normal view. Similarly, you can use partials from other models/controllers in the normal way.&lt;br /&gt;&lt;br /&gt;Finally &lt;code&gt;ActionMailer&lt;/code&gt; sends the e-mail. It needs to know your your mail settings, which it will collect from a file &lt;code&gt;mail.rb&lt;/code&gt; in &lt;code&gt;config/initializers&lt;/code&gt;. This might look something like this:&lt;br /&gt;&lt;pre&gt;# Email settings&lt;br /&gt;ActionMailer::Base.delivery_method = :smtp&lt;br /&gt;ActionMailer::Base.smtp_settings = {&lt;br /&gt;  :address =&gt; "smtp.mydomain.com",&lt;br /&gt;  :port =&gt; 25,&lt;br /&gt;  :domain =&gt; "mydomain.com",&lt;br /&gt;  :authentication =&gt; :login,&lt;br /&gt;  :user_name =&gt; "rails",&lt;br /&gt;  :password =&gt; "secret"&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;You can use your helper files in your mail views just like your normal views, just remember to declare them at the top of MyMailer:&lt;br /&gt;&lt;pre&gt;helper :application&lt;/pre&gt;&lt;br /&gt;The one slight difference is that you cannot do &lt;code&gt;helper :all&lt;/code&gt;. I imagine an oversight in Rails.&lt;br /&gt;&lt;br /&gt;Attachments can be added easily:&lt;br /&gt;&lt;pre&gt;  attachment "application/rtf" do |a|&lt;br /&gt;  a.body = File.read 'some_file.rtf'&lt;br /&gt;  a.filename = 'samples.rtf'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;br /&gt;You can test your mailer. Rails will have generated a default unit test (no functional testing as there is no controller for a mailer).&lt;br /&gt;&lt;pre&gt;require 'test_helper'&lt;br /&gt;&lt;br /&gt;class MyMailerTest &amp;lt; ActionMailer::TestCase&lt;br /&gt;tests MyMailer&lt;br /&gt;def test_send_book&lt;br /&gt;  @expected.subject = 'MyMailer#send_book'&lt;br /&gt;  @expected.body    = read_fixture('send_book')&lt;br /&gt;  @expected.date    = Time.now&lt;br /&gt;&lt;br /&gt;  assert_equal @expected.encoded,&lt;br /&gt;    MyMailer.create_send_book(@expected.date).encoded&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;NB: The generated unit test includes a statement &lt;code&gt;tests MyMailer&lt;/code&gt;. This seems to just invoke &lt;code&gt;write_inheritable_attribute&lt;/code&gt;, which appears to make a copy of the class variables in te superclass in the subclass.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7642223589479513136?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7642223589479513136/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7642223589479513136' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7642223589479513136'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7642223589479513136'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/01/rails-mailer.html' title='Rails Mailer'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-8952296575931029989</id><published>2009-01-04T20:46:00.011Z</published><updated>2010-03-22T11:52:11.251Z</updated><title type='text'>Exception Handling</title><content type='html'>You can define your own exceptions in Ruby very easily, just extend a suitable class (that is, StandardError or any of its sub-classes):&lt;br /&gt;&lt;pre&gt;class MyError &amp;lt; StandardError&lt;br /&gt;&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;To see how exceptions are handled, let us look at this example:&lt;br /&gt;&lt;pre&gt;try_counter = 0&lt;br /&gt;begin&lt;br /&gt; try_counter += 1&lt;br /&gt; puts 'Here 1'&lt;br /&gt; raise MyError.new "Text" unless try_counter &gt; 5&lt;br /&gt; puts 'Here 2'&lt;br /&gt;rescue MyError&lt;br /&gt; puts 'Here 3 - MyError encountered'&lt;br /&gt; retry&lt;br /&gt;rescue StandardError&lt;br /&gt; puts "Here 4 - Other error encountered (#{$!.inspect})" + caller.inspect&lt;br /&gt; raise&lt;br /&gt;else&lt;br /&gt; puts 'Here 5 - No errors'&lt;br /&gt;ensure&lt;br /&gt; puts 'Here 6 - Always done'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Exceptions are handled by blocks. The risky code goes into the first chunk of the block. If an exception is encountered, the program will jump to the end of that chunk and look for an appropriate action. In the above example, it will first look at &lt;code&gt;rescue MyError&lt;/code&gt;. If the exception is of the &lt;code&gt;MyError&lt;/code&gt; class - or a sub-class - then the program will not run the code folling the rescue. Note that you can list multiple exception classes, separated by commas.&lt;br /&gt;&lt;br /&gt;Otherwise, it will look further. The next rescue is for &lt;code&gt;StandardError&lt;/code&gt;, so this will catch all errors of the &lt;code&gt;StandardError&lt;/code&gt; type or its sub-classes - except for &lt;code&gt;MyClass&lt;/code&gt;, as that would have been caught earlier. All rescuable exceptions must inherit from &lt;code&gt;StandardError&lt;/code&gt; (but see later), so this is set up to catch all exceptions, but that need not be the case; uncaught exceptions will be passed on up the stack to whatever else might handle them.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;else&lt;/code&gt; chunk will get performed after the initial chunk has completed successfully (i.e., without raising an exception). Finally, the &lt;code&gt;ensure&lt;/code&gt; chunk gets performed whatever the outcome.&lt;br /&gt;&lt;br /&gt;An exception is raised using the &lt;code&gt;raise&lt;/code&gt; keyword. Exceptions are just objects, so are instantiated just like any other object. They typically take a string parameter, which you can use to give a descriptive message. Alternatively, you use this form:&lt;br /&gt;&lt;pre&gt;raise MyError.new "Test"&lt;br /&gt;raise MyError, "Text", caller&lt;br /&gt;raise MyError, "Text"&lt;br /&gt;raise "Text"     # For the default RuntimeError&lt;/pre&gt;&lt;br /&gt;You can put a &lt;code&gt;retry&lt;/code&gt; in a rescue chunk, as in the example above. The program will jump back to the start of the block, and start again. In the second &lt;code&gt;rescue&lt;/code&gt; chunk, there is a &lt;code&gt;raise&lt;/code&gt; on its own. This will pass the exception ouside of the block, to be handled by some higher up error handling system.&lt;br /&gt;&lt;br /&gt;Also in that chunk, note that the &lt;code&gt;$!&lt;/code&gt; code is the exception. If you prefer, you can set your own name for this.&lt;br /&gt;&lt;pre&gt;rescue StandardError =&gt; err&lt;br /&gt; puts "Here 4 - Other error encountered (#{err.inspect})" + caller.inspect&lt;br /&gt;raise&lt;/pre&gt;Here is the output from the first example:&lt;br /&gt;&lt;pre&gt;Here 1&lt;br /&gt;Here 3 - MyError encountered&lt;br /&gt;Here 1&lt;br /&gt;Here 3 - MyError encountered&lt;br /&gt;Here 1&lt;br /&gt;Here 3 - MyError encountered&lt;br /&gt;Here 1&lt;br /&gt;Here 3 - MyError encountered&lt;br /&gt;Here 1&lt;br /&gt;Here 3 - MyError encountered&lt;br /&gt;Here 1&lt;br /&gt;Here 2&lt;br /&gt;Here 5 - No errors&lt;br /&gt;Here 6 - Always done&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Stack Trace&lt;/span&gt;&lt;br /&gt;To see the stack trace, use the &lt;code&gt;backtrace&lt;/code&gt; method. This returns an array of strings. To just see the top dozen entries, you could use this:&lt;br /&gt;&lt;pre&gt;$!.backtrace[0..12] * "\n"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Exceptions that do not inherit from StandardError&lt;/strong&gt;&lt;br /&gt;The superclass for all exceptions is &lt;code&gt;Exception&lt;/code&gt;. The theory is that all exceptions that a program should be expected to recover from are either &lt;code&gt;StandardError&lt;/code&gt; or a subclass of it, which is why I described them as "rescuable exceptions " earlier. If no exception is specified, rescue will default to &lt;code&gt;StandardError&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;However, there may be times you want to recover from other exceptions. A particular example I came across is a &lt;code&gt;SyntaxError&lt;/code&gt; thrown by ERB. The offending syntax was in a data file, not my application; my application should have caught the error, and reported it back to the user. This is entirely different to a syntax error in my code, and in my opinion ERB should throw its own exceptions that inherit from &lt;code&gt;StandardError&lt;/code&gt;. Time-out errors are another example, as discussed &lt;a href="http://jerith.livejournal.com/40063.html"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;To catch &lt;em&gt;all&lt;/em&gt; exceptions use:&lt;br /&gt;&lt;pre&gt;rescue Exception&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The rescue statement modifier&lt;/strong&gt;&lt;br /&gt;Rescue can be used in a way analogous to if and unless. For example:&lt;br /&gt;&lt;pre&gt;test rescue do_stuff&lt;/pre&gt;&lt;br /&gt;This statement will run the method test, and if it encounters an error (specifically StandardError or subclasses) it will invoke do_stuff. You can use this to assign a default value if a method fails, like this:&lt;br /&gt;&lt;pre&gt;s = test rescue "Default value"&lt;/pre&gt;&lt;br /&gt;The rescue stament returns the value "Default Value". You could write it with brackets, which might help make sense of it:&lt;br /&gt;&lt;pre&gt;s = (test rescue "Default value")&lt;/pre&gt;&lt;br /&gt;You can concatenate statement with semi-colons, but cannot use blocks.&lt;br /&gt;&lt;pre&gt;s = test rescue do_stuff; "Default value"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://whynotwiki.com/Ruby_/_Exception_handling"&gt;http://whynotwiki.com/Ruby_/_Exception_handling&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Catch and Throw&lt;/strong&gt;&lt;br /&gt;The catch and throw facility in Ruby is not really exception handling at all, though it does have similarities. As it shares keywords with Java exception handling, it seems to get lumped into any discussion on exceptions. This page is no different.&lt;br /&gt;&lt;br /&gt;Calling a &lt;code&gt;throw&lt;/code&gt; will interrupt the program flow, causing it to jump to the named &lt;code&gt;catch&lt;/code&gt;. Use this format to set up a catch block. Any time &lt;code&gt;throw :my_label&lt;/code&gt; is called within the block (including within methods called from the block).&lt;br /&gt;&lt;pre&gt;catch :my_label do&lt;br /&gt; do_stuff&lt;br /&gt;throw :my_label&lt;br /&gt; do_not_do this_stuff&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can use the throw to return a value to catch (which will be nil otherwise).&lt;br /&gt;&lt;pre&gt;value = catch :my_label do&lt;br /&gt; do_stuff&lt;br /&gt;throw :my_label, "My result"&lt;br /&gt; do_not_do this_stuff&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-8952296575931029989?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/8952296575931029989/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=8952296575931029989' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8952296575931029989'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8952296575931029989'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2009/01/exception-handling.html' title='Exception Handling'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4657758140130132803</id><published>2008-12-12T21:44:00.006Z</published><updated>2009-03-27T15:52:49.880Z</updated><title type='text'>Integration testing</title><content type='html'>I found this to be quite frustrating. Integration testing appears to be a relatively recent addition to Rails (since 1.1 I think), and pehaps for that reason there is not much on the web that explains the basics of how to do it. Coupled to that, my application is using an authentication system that I copied from a web site, and so I was just not that familiar with what is supposed to happen (at least, when I started; I know it a lot better after going through this). Also, the authentication system has some odd quirks, like defining session (rather than sessions) as a route, for a controller called sessions_controller.&lt;br /&gt;&lt;br /&gt;Integration testing can be thought of functional testing for multiple controllers. This allows you to set up involved "stories" in which the user does a sequence of actions. Rails automatically generates unit and functional tests for you when you create a scaffold, but not an integration test (as it is not specific to one model/controller). However, there is a script to do the job for you.&lt;br /&gt;&lt;pre&gt;ruby script/generate integration_test GeneralStories&lt;/pre&gt;&lt;br /&gt;Here is a test for the user authentication mentioned before:&lt;br /&gt;&lt;pre&gt;  def test_authentication&lt;br /&gt;   user_bob = {:login =&gt; 'bob', :username =&gt; 'Robert',&lt;br /&gt;       :email =&gt; 'test@here.com', :password =&gt; '12345678',&lt;br /&gt;       :password_confirmation =&gt; '12345678', }&lt;br /&gt;   new_password = 'new_secret'&lt;br /&gt; &lt;br /&gt;   goes_to_home_page&lt;br /&gt;   goes_to_login&lt;br /&gt;   fails_to_log_in_with user_bob&lt;br /&gt;   goes_to_signup&lt;br /&gt;   signs_up_with user_bob&lt;br /&gt;   goes_to_login&lt;br /&gt;   logs_in_with user_bob&lt;br /&gt;   goes_to_change_password&lt;br /&gt;   changes_password user_bob, new_password&lt;br /&gt;   logs_out&lt;br /&gt;   goes_to_login&lt;br /&gt;   logs_in_with user_bob&lt;br /&gt;   goes_to_home_page&lt;br /&gt; end&lt;/pre&gt;&lt;br /&gt;The code here is easy enough. A test method has to start &lt;code&gt;test_&lt;/code&gt; so Rails knows it is a test. First a hash is set up with details for a user, as well as a new password. Thereafter, it runs through a sequence of methods, each one corresponding to a single page download to the user (purely because that seems a convenient way to break it up). Reading down the sequence, we can read the story. The user goes to the home page, attempts to log in, but fails, then signs up, successfully logs in, changes his password, logs off, and logs on again, ending up back at the home page.&lt;br /&gt;&lt;br /&gt;All the tricky stuff is, of course, hidden away in those methods. I am just going to look at the two involved in changing the password to illustrate the methodology.&lt;br /&gt;&lt;pre&gt;def goes_to_change_password&lt;br /&gt; get "/change_password"&lt;br /&gt; assert_equal 200, status&lt;br /&gt; assert_equal "/change_password", path&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This corresponds to the user clicking on the "Change Password" link. The get command is equivalent to an HTTP GET. You then check the HTTP result is 200, and the returned page is correct. The next method is rather more complicated.&lt;br /&gt;&lt;pre&gt;def changes_password(user_options, new_password)&lt;br /&gt; post "/accounts/update",&lt;br /&gt;      :old_password =&gt; user_options[:password],&lt;br /&gt;      :password =&gt; new_password,&lt;br /&gt;      :password_confirmation =&gt; new_password&lt;br /&gt; follow_redirect!&lt;br /&gt; assert_equal 'Password successfully updated.', flash[:notice]&lt;br /&gt; assert_equal "/", path&lt;br /&gt; assert_equal 200, status&lt;br /&gt; user_options[:password] = new_password&lt;br /&gt; user_options[:password_confirmation] = new_password&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Now the post command is invoked, for HTTP POST. The values on the form are sent in the form of a hash. Rails usually expects a hash of a hash here, which would look like this (and in the controller would be accessed with &lt;code&gt;params[:user]&lt;/code&gt;):&lt;br /&gt;&lt;pre&gt;  post "/accounts/update",&lt;br /&gt;    user =&gt; {:old_password =&gt; user_options[:password],&lt;br /&gt;             :password =&gt; new_password,&lt;br /&gt;             :password_confirmation =&gt; new_password}&lt;/pre&gt;&lt;br /&gt;I am not sure why my authentication system was set up differently; perhaps for older versions of Rails. If the action is successful, the user is redirected, and we want to see where that goes, so the next statement, &lt;code&gt;follow_redirect!&lt;/code&gt;, does just that. Then we check everything: the flash notice should confirm the change, the path should be at the root and the HTTP status should be 200. Finally, a little bit of house-keeping; the user hash is updated with the new password ready to test logging on in a later step.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Multiple Sessions&lt;/strong&gt;&lt;br /&gt;In the background, Rails has a session object on the go, and this allows your test to proceed. If you want to you can invoke the session explicitly. One reason to do that would be to test what happens if multiple users are logged in at the same time (though I am suspicious that people use this when it is not necessary). It goes something like this (based in part on code &lt;a href="http://weblog.jamisbuck.org/2006/3/9/integration-testing-in-rails-1-1"&gt;here&lt;/a&gt;):&lt;br /&gt;&lt;pre&gt;def test_signup_new_person&lt;br /&gt; user_bob = {:login =&gt; 'bob', :username =&gt; 'Robert',&lt;br /&gt;    :email =&gt; 'test1@here.com', :password =&gt; '12345678',&lt;br /&gt;    :password_confirmation =&gt; '12345678'}&lt;br /&gt; user_mary = {:login =&gt; 'mary', :username =&gt; 'Mary',&lt;br /&gt;    :email =&gt; 'test2@here.com', :password =&gt; '12345678',&lt;br /&gt;    :password_confirmation =&gt; '12345678'}&lt;br /&gt; new_password = 'new_secret'&lt;br /&gt;&lt;br /&gt; open_session do bob&lt;br /&gt;   open_session do mary&lt;br /&gt;     bob.extend(MyTestingDSL)&lt;br /&gt;     mary.extend(MyTestingDSL)&lt;br /&gt;&lt;br /&gt;     bob.goes_home&lt;br /&gt;     bob.goes_to_login&lt;br /&gt;     bob.fails_to_log_in_with user_bob&lt;br /&gt;     bob.goes_to_signup&lt;br /&gt;     bob.signs_up_with user_bob&lt;br /&gt;     mary.goes_to_signup&lt;br /&gt;     bob.goes_to_login&lt;br /&gt;     bob.logs_in_with user_bob&lt;br /&gt;     mary.signs_up_with user_mary&lt;br /&gt;     bob.goes_to_change_password&lt;br /&gt;     bob.changes_password user_bob, new_password&lt;br /&gt;     mary.goes_to_login&lt;br /&gt;     mary.logs_in_with user_mary&lt;br /&gt;     bob.logs_out&lt;br /&gt;     bob.goes_to_login&lt;br /&gt;     bob.logs_in_with user_bob&lt;br /&gt;     bob.goes_home&lt;br /&gt;   end&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The test itself is more or less the same, except that the sequence is wrapped up in a block for &lt;code&gt;open_session&lt;/code&gt;, and the session is addressed directly. This allows two sessions to be set up, bob and mary. The methods are set up the same, but again are wrapped up, this time in a module called &lt;code&gt;MyTestingDSL&lt;/code&gt;. The module is mixed in to the session before the methods are invoked.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Finally...&lt;/strong&gt;&lt;br /&gt;I found it helpful to end my assertion with a call to this method:&lt;br /&gt;&lt;pre&gt;def flash_me&lt;br /&gt; "Error encountered. Flash[:error]=#{flash[:error]} Flash[:notice]=#{flash[:notice]}"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;For example:&lt;br /&gt;&lt;pre&gt;assert_equal 200, status, flash_me&lt;/pre&gt;&lt;br /&gt;If the assertion fails, you will get told the contents of flash. The method definition needs to be inside the module, if you are using sessions explicitly.&lt;br /&gt;&lt;br /&gt;I found trouble-shooting a test failure to be something of a nightmare. The test informs you at which line in the test line it failed, but that gives you no clue about when in your actual code the problem is. It will report the same error (&lt;200&gt; expected but was &lt;500&gt;) for anything from an action that is not recognised, to an exception thrown in your model or a misnamed column. The best solution I found was to pepper the code with statements assigning values to the flash, which would then show up using the flash_me method above. Here is an example (with additional lines in red):&lt;br /&gt;&lt;pre&gt;def qualify&lt;br /&gt;  &lt;span style="color:red;"&gt;flash[:notice] = 'here'&lt;br /&gt;  begin&lt;/span&gt;&lt;br /&gt;  @worksheet_meta_data = WorksheetMetaData.find(params[:id])&lt;br /&gt;  &lt;span style="color:red;"&gt;flash[:error] = '@worksheet_meta_data = nil' if @worksheet_meta_data.nil?&lt;/span&gt;&lt;br /&gt;  s = @worksheet_meta_data.qualify current_user.username&lt;br /&gt;  if s.nil?&lt;br /&gt;    flash[:notice] = "WorksheetMetaData was qualified (#{@worksheet_meta_data.qualified_by})."&lt;br /&gt;  else&lt;br /&gt;    flash[:error] = "Qualification failed: #{s}"&lt;br /&gt;  end&lt;br /&gt;  &lt;span style="color:red;"&gt;rescue Exception =&gt; ex&lt;br /&gt;    flash[:error] = "ex=#{ex}"&lt;br /&gt;  end&lt;/span&gt;&lt;br /&gt;  redirect_to(@worksheet_meta_data)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I also commented out the redirect! statement, so after the get or post, there is the assert, with a flash_me to see the result. The first extra line will confirm that the method is being invoked (are you using the right controller, action, and id; these might give a 404 error if not). Then everything up to the redirect is wrapped in a rescue block so any errors thrown get recorded in flash[:error]. Inside the block, I check &lt;br /&gt;&lt;br /&gt;I would be interested to hear of any better ideas.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4657758140130132803?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4657758140130132803/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4657758140130132803' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4657758140130132803'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4657758140130132803'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/12/integration-testing.html' title='Integration testing'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7827364922189579908</id><published>2008-12-10T21:27:00.004Z</published><updated>2009-01-19T11:03:01.352Z</updated><title type='text'>Ruby Classes</title><content type='html'>In Ruby, everything is an object. You can find the class of an object with &lt;code&gt;my_object.class&lt;/code&gt;, which returns an object of the &lt;code&gt;Class&lt;/code&gt; class.&lt;br /&gt;&lt;pre&gt;10.class  # =&gt; Fixnum&lt;br /&gt;10.class.class # =&gt; Class&lt;br /&gt;"Hello World".class # =&gt; String&lt;/pre&gt;&lt;br /&gt;If you do not have an instance of a class, you can determine the name of the class using the &lt;code&gt;inspect&lt;/code&gt; method (this might be useful if you are in a class method in a super class and want to know the subclass).&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;superclass&lt;/code&gt; method will produce the superclass.&lt;br /&gt;&lt;pre&gt;10.class.superclass # =&gt; Integer&lt;br /&gt;10.class.superclass.superclass # =&gt; Numeric&lt;br /&gt;10.class.superclass.superclass.superclass # =&gt; Object&lt;/pre&gt;&lt;br /&gt;As in Java, everything inherits from &lt;code&gt;Object&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;You can check if an object is of a certain class using the &lt;code&gt;is_a?&lt;/code&gt; method. This will return &lt;code&gt;true&lt;/code&gt; if the object is of the given class or of a subclass of it.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;"Hello World".is_a? String # =&gt; true&lt;br /&gt;"Hello World".is_a? Fixnum # =&gt; false&lt;br /&gt;"Hello World".is_a? Object # =&gt; true&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;What methods are there?&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;methods&lt;/code&gt; method returns an array of method names for an object, while a call on &lt;code&gt;methods&lt;/code&gt; from the class will produce an array of class methods.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;"Hello".methods&lt;br /&gt;String.methods&lt;/pre&gt;&lt;br /&gt;There are also methods that list more particular methods, such as &lt;code&gt;public_instance_methods&lt;/code&gt; or &lt;code&gt;private_methods&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;You can also check if an object has an associated method with the &lt;code&gt;respond_to?&lt;/code&gt; or &lt;code&gt;method_defined?&lt;/code&gt; methods. Unlike &lt;code&gt;methods&lt;/code&gt;, these two methods will not find private methods. The &lt;code&gt;respond_to?&lt;/code&gt; method really does what it say - it tells you if the object will respond to the method call, rather than if the method exists. Often an object can respond to method calls where there is no method present using the &lt;code&gt;method_missing&lt;/code&gt; functionality (discussed &lt;a href="http://strugglingwithruby.blogspot.com/2008/07/dynamic-methods.html"&gt;here&lt;/a&gt;). Rails uses this a lot. For a model, Post, calling &lt;code&gt;Post.methods&lt;/code&gt; will locate no &lt;code&gt;find&lt;/code&gt; methods, but the &lt;code&gt;respond_to?&lt;/code&gt; method confirms they are there. &lt;code&gt;method_defined?&lt;/code&gt; will tell you if the method actually exists.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;"Hello".respond_to? 'length' # =&gt; true&lt;br /&gt;String.respond_to? 'constants' # =&gt; true&lt;br /&gt;Post.respond_to? 'find_by_name' # =&gt; true&lt;br /&gt;Post.method_defined? 'find_by_name' # =&gt; false&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/ospace.html"&gt;http://www.ruby-doc.org/docs/ProgrammingRuby/html/ospace.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Dynamically adding a method&lt;/strong&gt;&lt;br /&gt;You can add a method to a class at runtime, using the &lt;code&gt;define_method&lt;/code&gt; method. Note that this method is private (so the first attempt below results in an error), and so must be invoked with the &lt;code&gt;send&lt;/code&gt; method.&lt;br /&gt;&lt;pre&gt;a = "what".class.define_method('hello') {p 'Hello World'}&lt;br /&gt;# =&gt; NoMethodError: private method `define_method' called for String:Class&lt;br /&gt;a = "what".class.send(:define_method, 'hello') {p 'Hello World'}&lt;br /&gt;# =&gt; #&amp;lt;Proc:0x08cb9294@(irb):17&gt;&lt;br /&gt;irb(main):018:0&gt; "say hello".hello&lt;br /&gt;# =&gt; Hello World&lt;/pre&gt;&lt;br /&gt;You can even replace existing methods:&lt;br /&gt;&lt;pre&gt;"what".length&lt;br /&gt;=&gt; 4&lt;br /&gt;a = "random".class.send(:define_method, 'length') { 10 }&lt;br /&gt;=&gt; #&amp;lt;Proc:0x08caaf28@(irb):21&gt;&lt;br /&gt;"what".length&lt;br /&gt;=&gt; 10&lt;/pre&gt;&lt;br /&gt;Alternatively (and more simply), you can define methods for existing classes just like you would for your own class. The first example could be done like this:&lt;br /&gt;&lt;pre&gt;class String&lt;br /&gt;  def hello&lt;br /&gt;    p 'Hello World'&lt;br /&gt;  end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;I can see security issues here if someone can change how your classes' behave at runtime, and how do you comprehensively unit test if you cannot be sure how the String class behaves? All part of the fun of a dynamic language...&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;ObjectSpace&lt;/strong&gt;&lt;br /&gt;&lt;code&gt;ObjectSpace&lt;/code&gt; is the Ruby reflection mechanism. It is a module that tracks all the current objects. You can list them with this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;ObjectSpace.each_object{ i puts i}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I had over 8000 objects in one IRB session. You can specify the class of an object to list, for example, this will list all objects of the Class class (only 466 of them):&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;ObjectSpace.each_object(Class) { i puts i}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Creating new objects dynamically&lt;/strong&gt;&lt;br /&gt;You can use the &lt;code&gt;ObjectSpace&lt;/code&gt; to create a new object from a string containing the class name (see &lt;a href="http://angrez.blogspot.com/2006/11/using-reflection-in-ruby.html"&gt;here&lt;/a&gt;), but I prefer using the &lt;code&gt;eval&lt;/code&gt; method. &lt;code&gt;eval&lt;/code&gt; simply interprets a given string as Ruby (like the synonymous method in JavaScript). The &lt;code&gt;eval&lt;/code&gt; method is none too fast, but I do not know how it compares to using &lt;code&gt;ObjectSpace&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def create_object class_name&lt;br /&gt;  eval("#{class_name}.new")&lt;br /&gt;end&lt;/pre&gt;&lt;/proc:0x08caaf28@(irb):21&gt;&lt;/proc:0x08cb9294@(irb):17&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7827364922189579908?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7827364922189579908/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7827364922189579908' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7827364922189579908'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7827364922189579908'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/12/ruby-classes.html' title='Ruby Classes'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-2135287405739363490</id><published>2008-12-05T20:45:00.007Z</published><updated>2009-03-05T15:32:50.083Z</updated><title type='text'>Ruby Methods Part 2 - Not Overloading!</title><content type='html'>&lt;a href="http://en.wikipedia.org/wiki/Method_overloading"&gt;Method overloading&lt;/a&gt; is a common feature of several object-orientated languages. It allows the same name to be used for methods that perform the same, but accept different parameter types. Here is an example in Java:&lt;br /&gt;&lt;pre&gt;  // Method overloading in Java&lt;br /&gt; public int myMethod(String name, int age, int shoeSize) {&lt;br /&gt;   // do stuff&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public int myMethod(String name, int shoeSize) {&lt;br /&gt;   myMethod(name, 0, shoeSize) {&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public int myMethod(int age, int shoeSize) {&lt;br /&gt;   myMethod("", age, shoeSize) {&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; public int myMethod() {&lt;br /&gt;   myMethod("", 0, 0) {&lt;br /&gt; }&lt;br /&gt;&lt;br /&gt; // Invoking&lt;br /&gt; public int main(String[] args) {&lt;br /&gt;   myMethod("F2Andy", 43, 8);&lt;br /&gt;   myMethod("F2Andy", 8);&lt;br /&gt;   myMethod(43, 8);&lt;br /&gt;   myMethod();&lt;br /&gt; }&lt;/pre&gt;&lt;br /&gt;Ruby does not support method overloading, something I found very surprising at first. I suspect the reason is the way Ruby handles objects. Java is very strict that what gets sent to a method is exactly what the method expects. That gives (I would imagine) more robustness, but at the loss of flexibility.&lt;br /&gt;&lt;br /&gt;Ruby has what could be described as "method over-writing" instead of overloading. In this example, the second test method over-writes the first:&lt;br /&gt;&lt;pre&gt;def test s&lt;br /&gt; puts "hello test"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def test&lt;br /&gt; puts "goodbye test"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test                # Causes "goodbye test" to be printed&lt;br /&gt;#test "my string"   # Causes an error:&lt;br /&gt;   # wrong # of arguments(1 for 0) (ArgumentError)&lt;/pre&gt;See here for how to use alias if you still need to access the old methods:&lt;br /&gt;&lt;a href="http://www.zweknu.org/blog/index.rhtml?start=77&amp;amp;"&gt;http://www.zweknu.org/blog/index.rhtml?start=77&amp;amp;&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Default values and dynamic typing&lt;/strong&gt;&lt;br /&gt;Ruby has four tricks to mimic method overloading, and I am going to bundle the first two together. The first is default values in the method definition. Simply give a parameter a default value and it becomes optional. The second is the way Ruby handles objects; dynamic typing. Ruby does not care what sort of object you throw at a method, leaving the method writer the chance to handle different classes in different ways. In the next example the method has a default value - "default" - but the method is written in such a way that it will accept any class of object:&lt;br /&gt;&lt;pre&gt;def test t = 'default'&lt;br /&gt; puts "goodbye test t=#{t}"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test           # =&gt; "goodbye test t=default"&lt;br /&gt;test 34        # =&gt; "goodbye test t=34"&lt;/pre&gt;&lt;br /&gt;Something to consider, then, is how you handle unexpected objects in your class. One way is to ignore the issue, making the assumption that the method user knows what he is doing and any problems will be caught by the Ruby system.&lt;br /&gt;&lt;pre&gt;def test t = 'default'&lt;br /&gt; puts 'goodbye test t=' + t&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test "one"     # =&gt; "goodbye test t=one"&lt;br /&gt;#test 2        # =&gt; can't convert Fixnum&lt;br /&gt;              # into String (TypeError)&lt;/pre&gt;&lt;br /&gt;Let us look at another example to see what options we have:&lt;br /&gt;&lt;pre&gt;def test n&lt;br /&gt; puts n.abs&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test -4          # =&gt; 4&lt;br /&gt;test 2           # =&gt; 2&lt;br /&gt;#test "three"    # =&gt; undefined method `abs'&lt;br /&gt;                # for "three": String (NoMethodError)&lt;/pre&gt;&lt;br /&gt;Rather than relying on your own method calls to generate errors, you might prefer to check that what you receive in your method is what you are expecting. You can then be quite clear about what exceptions your method is throwing, and more importantly, you will not have exceptions thrown half way through you method leaving the system in an unpredictable state.&lt;br /&gt;&lt;pre&gt;def test n&lt;br /&gt; raise StandardError.new("Oops, not a Fixnum") unless n.is_a? Fixnum&lt;br /&gt; puts n.abs&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test -4          # =&gt; 4&lt;br /&gt;test 2           # =&gt; 2&lt;br /&gt;test "three"     # =&gt; Oops, not a Fixnum&lt;br /&gt;                # (StandardError)&lt;/pre&gt;&lt;br /&gt;Then again, perhaps you do not care what class the object is. The important question is whether it will behave as you expect. Instead of testing that it is of the right class, you could test that it responds to the appropriate methods calls. In this next example, a new method, &lt;code&gt;abs&lt;/code&gt;, is added to the String class (how that is done was the subject of another post). Now the test method checks that the object it is given will respond to the necessary method call. This technique offers a lot more flexibility, but does rely on the API user sending sensible objects to the method. Does it really make sense that a string should return the ASCII code of the first character when asked for its absolute value? However, I would say that that is up to the API user; he has the responsibility now of ensuring the object he sends makes sense. You would need to check for each and every method call in your code.&lt;br /&gt;&lt;pre&gt;class String&lt;br /&gt; def abs&lt;br /&gt;   self[0]&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def test n&lt;br /&gt; raise StandardError.new('Oops, object does not respond to abs') unless n.respond_to? 'abs'&lt;br /&gt; puts n.abs&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;puts "three".abs     # =&gt; 116&lt;br /&gt;test -4              # =&gt; 4&lt;br /&gt;test 2               # =&gt; 2&lt;br /&gt;test "three"         # =&gt; 116&lt;/pre&gt;&lt;br /&gt;What would have happened if I had defined the &lt;code&gt;abs&lt;/code&gt; method on &lt;code&gt;String&lt;/code&gt; to return a string, rather than a Fixnum?&lt;br /&gt;&lt;strong&gt;Using hashes for parameters&lt;/strong&gt;&lt;br /&gt;The third trick is to use a hash, and this is done throughout Rails. In the next example, the method expects a hash. Note that the default is set to be an empty hash, to avoid errors with nil.&lt;br /&gt;&lt;pre&gt;def test options = {}&lt;br /&gt; puts "hello #{options[:name]}"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test                     # =&gt; "hello "&lt;br /&gt;test "here"              # =&gt; "hello "&lt;br /&gt;test :name =&gt; 'F2Andy'   # =&gt; "hello F2Andy"&lt;/pre&gt;&lt;br /&gt;Compared to method overloading, there are advantages on both sides. If you have an existing method and you want to add overloading, it is no problem in Java. In Ruby, chances are your existng method is not expecting a hash and you either have to change your existing method calls or write the new method to expect either a hash or the original type. However, if your Ruby method already accepts a hash, adding more parameters becomes trivial - just add them to method calls if desired, and use in the method code where needed.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Variadic functions&lt;/strong&gt;&lt;br /&gt;Finally, Ruby supports variadic functions. These are methods that accept a vaiable number of parameters. In Ruby this is indicated by an asterix in the method parameter list, before the last parameter. This will then become an array holding all the "left over" values. Here is an example:&lt;br /&gt;&lt;pre&gt;def vari_method name, *values&lt;br /&gt; puts name&lt;br /&gt; values.each { |x|&lt;br /&gt;   puts " -#{x}"&lt;br /&gt; }&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;vari_method 'fruit', 'apple', 'banana', 'pear'&lt;/pre&gt;&lt;br /&gt;When vari_method is invoked, 'fruit' goes into the name variable, and the three other strings are collected into a single array, values. The method prints the name, then lists each member of the array. There is no reason for the members of the array to be of the same class or in any way connected to each other.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-2135287405739363490?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/2135287405739363490/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=2135287405739363490' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2135287405739363490'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2135287405739363490'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/12/ruby-methods-part-2.html' title='Ruby Methods Part 2 - Not Overloading!'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-936479808857350570</id><published>2008-12-04T21:36:00.006Z</published><updated>2010-03-15T14:55:40.166Z</updated><title type='text'>Ruby Methods Part 1 - The Basics</title><content type='html'>A Ruby method definition starts with the keyword &lt;code&gt;def&lt;/code&gt; followed by the method name and the parameter names, and ends with the keyword &lt;code&gt;end&lt;/code&gt;.&lt;br /&gt;&lt;pre&gt;def test&lt;br /&gt;puts "Hello World"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;test   # Causes "Hello World" to be printed&lt;/pre&gt;&lt;br /&gt;Note that unlike Java and C#, Ruby does not require the return type or the parameter types to be stated. Every Ruby method returns a value. In the above example, &lt;code&gt;puts&lt;/code&gt; returns nil, and as this is the last statement in the method test, test will also return nil. The &lt;code&gt;return&lt;/code&gt; keyword is entirely optional (though necessary if you want to jump out of the middle of a method, of course).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Visibility&lt;/strong&gt;&lt;br /&gt;By default, all methods are public; they can be accessed from anywhere by anything.&lt;br /&gt;&lt;br /&gt;Private methods can only be accessed from with the class and (unlike Java et al) its subclasses. That said, you can access private methods from anywhere using the send method, or modify their visibility on-the-fly, so it would seem that this is more advisory than anything else; the API writer is telling you that you probably should not use those methods.&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;private&lt;/code&gt; keyword indicates that all subsequent methods (until public or protected is encounted) will be private.&lt;br /&gt;&lt;pre&gt;class MyClass&lt;br /&gt;def public_method&lt;br /&gt; puts "In public_method"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# You can access private methods within the class&lt;br /&gt;def private_via_public_method&lt;br /&gt; puts "private_via_public_method"&lt;br /&gt; private_method&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;private  # Flags all subsequent methods&lt;br /&gt;        # as private&lt;br /&gt;&lt;br /&gt;def private_method&lt;br /&gt; puts "In private_methodstance_method"&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;class MySubClass &amp;lt; MyClass&lt;br /&gt;# You can also access private methods&lt;br /&gt;# within any subclass&lt;br /&gt;def private_via_subclass_public_method&lt;br /&gt; puts "private_via_subclass_public_method"&lt;br /&gt; private_method&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;mc = MyClass.new&lt;br /&gt;mc.private_via_public_method&lt;br /&gt;mc.public_method&lt;br /&gt;#mc.protected_method    # Protected method&lt;br /&gt;                     # not visible&lt;br /&gt;#mc.private_method      # Private method&lt;br /&gt;                     # not visible&lt;br /&gt;&lt;br /&gt;mc.send :private_method # Private method&lt;br /&gt;                     # accessed with send&lt;br /&gt;&lt;br /&gt;# Visibility can be changed dynamically&lt;br /&gt;class MyClass&lt;br /&gt;public :private_method&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;mc.private_method      # Private method is&lt;br /&gt;                    # now visible&lt;/pre&gt;&lt;br /&gt;The third visibility type is protected, which is a little more esoteric. The protected visibility is very similar to private, except that protected allows you call method from a different object, as long as that object is of the same class or subclass. To put it another way, private is restricted to the specific object, protected is restricted to the class.&lt;br /&gt;&lt;pre&gt;class MyClass&lt;br /&gt;# You can access private methods on the&lt;br /&gt;# object within the class&lt;br /&gt;def private_via_public_method&lt;br /&gt; private_method&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# You can access protected methods on another&lt;br /&gt;# object within the class&lt;br /&gt;def protected_via_other_public_method&lt;br /&gt; mc = MyClass.new&lt;br /&gt; mc.protected_method&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# This will fail&lt;br /&gt;# You cannot access private methods on another&lt;br /&gt;# object, even within the class&lt;br /&gt;def private_via_other_public_method&lt;br /&gt; mc = MyClass.new&lt;br /&gt; mc.private_method&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;protected&lt;br /&gt;def protected_method&lt;br /&gt; puts "In protected_method"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;private&lt;br /&gt;def private_method&lt;br /&gt; puts "In private_methodstance_method"&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The important point here is that both private and protected methods can only be used with the class (or subclass), but that private methods are further restricted to calls that do not require the dot operator.&lt;br /&gt;&lt;br /&gt;As an aside, in Ruby all constants are public, and all variables are private&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Class methods&lt;/strong&gt;&lt;br /&gt;Class methods are methods that are applied to the class rather than to a specific instance of the class. The most important example of a class method is &lt;code&gt;new&lt;/code&gt;; in Rails the &lt;code&gt;find&lt;/code&gt; method is also used very frequently.&lt;br /&gt;&lt;pre&gt;s = String.new "My string"  # Equivalent to&lt;br /&gt;                              # s = "My string"&lt;br /&gt;post = Post.find :first     # gets the first record&lt;br /&gt;                         # from the posts table&lt;/pre&gt;&lt;br /&gt;As can be seen, class methods are invoked by using the class name, rather than the object, and as in the examples above they are often used to create or retrieve instances of the class.&lt;br /&gt;&lt;br /&gt;Class methods are written much like instance methods, but with the keyword &lt;code&gt;self&lt;/code&gt; before the method name. You cannot call a class method from an instance of the class, or call an instance method from the class itself. This does mean you can have a class method with the same name as an instance method.&lt;br /&gt;&lt;br /&gt;See the next section for an example of a class method.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The initialize method&lt;/strong&gt;&lt;br /&gt;I have already mentioned the &lt;code&gt;new&lt;/code&gt; class method. What this does is create a new instance of the object, and then it invokes the &lt;code&gt;initialize&lt;/code&gt; method, if it exists. The &lt;code&gt;initialize&lt;/code&gt; method is always private; there seems no way to change that. However, you can invoke it from within your class.&lt;br /&gt;&lt;br /&gt;The following code illustrates the use of &lt;code&gt;initialize&lt;/code&gt; and class methods.&lt;br /&gt;&lt;pre&gt;class MyClass&lt;br /&gt;def initialize&lt;br /&gt; puts "In initialize"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def self.class_method&lt;br /&gt; puts "In class_method"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def instance_method&lt;br /&gt; puts "In instance_method"&lt;br /&gt;end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;MyClass.class_method     # Prints "In class_method"&lt;br /&gt;mc = MyClass.new         # Would cause error; cannot call class methods on an object&lt;br /&gt;#mc.class_method         # Prints "In initialize"&lt;br /&gt;mc.instance_method       # Prints "In instance_method"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Class initialize method?&lt;/strong&gt;&lt;br /&gt;Sometimes you might want to do something to set up your class. You want it to run before any instances and created. I believe Rails does this for ActiveRecords, inspecting the database to see what fields are present, so it will know how to handle requests, rather than inspecting the database each time a request is made.&lt;br /&gt;&lt;br /&gt;There is no method that supports this, you just put your code straight into the class definition.&lt;br /&gt;&lt;pre&gt;class MyClass&lt;br /&gt;p 'This will be printed when the class is loaded'&lt;br /&gt;&lt;br /&gt;def initialize&lt;br /&gt; p 'This will be printed when an object is instantiated'&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Multiple return results&lt;/strong&gt;&lt;br /&gt;Pretty much every modern language allows you to send multiple arguments to a function/procedure/method. How many allow you to return multiple arguments? Certainly not the C derivatives, and really I cannot see why that should be so. At the machine code level, I would assume there is no difference. I would guess the reason is that C is based on a mathematical concept of functions, F = f(x,y,z), and Java and C# had followed suit.&lt;br /&gt;&lt;br /&gt;Not so Ruby, which allows you to return as many values as you like. Here is a trivial example to illustrate that:&lt;br /&gt;&lt;pre&gt;def test&lt;br /&gt;return return 1, 'two', 3&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;a, b = test&lt;br /&gt;p a # =&gt; 1&lt;br /&gt;p b # =&gt; "two"&lt;br /&gt;&lt;br /&gt;a, b, c, d = test&lt;br /&gt;p a # =&gt; 1&lt;br /&gt;p b # =&gt; "two"&lt;br /&gt;p c # =&gt; 3&lt;br /&gt;p d # =&gt; 4&lt;/pre&gt;&lt;br /&gt;Note that in this case the &lt;code&gt;return&lt;/code&gt; keyword is required. What is actually returned is an array containing each each return value. This can lead to confusion...&lt;br /&gt;&lt;pre&gt;def tester&lt;br /&gt;  return 3, 6&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def output x, y = nil&lt;br /&gt;  p "x=#{x} y=#{y}"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;x, y = tester&lt;br /&gt;output x, y&lt;br /&gt;# =&gt; "x=3 y=6"&lt;br /&gt;&lt;br /&gt;output tester&lt;br /&gt;# =&gt; "x=36 y="&lt;/pre&gt;&lt;br /&gt;The first call to tester correctly gets the two values assigned to the two variables. However, the second fails; the array is passed directly to the output method, which has no clue about the context, and just sees an array. What is really happening is a bit of trickery. Ruby does not pass back multiple values at all; it just passes back an array when multiple values are used with return. Meanwhile, at the other end, Ruby allows multiple varaibles to be set from an array.&lt;br /&gt;&lt;pre&gt;x, y = [7, 6]&lt;br /&gt;output x, y&lt;/pre&gt;&lt;br /&gt;Overall we have the illusion of muliple returns.&lt;br /&gt;&lt;br /&gt;blog on dynamically creating methods:&lt;br /&gt;&lt;a href="http://ola-bini.blogspot.com/2008/05/dynamically-created-methods-in-ruby.html"&gt;http://ola-bini.blogspot.com/2008/05/dynamically-created-methods-in-ruby.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-936479808857350570?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/936479808857350570/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=936479808857350570' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/936479808857350570'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/936479808857350570'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/12/ruby-methods-part-1-basics.html' title='Ruby Methods Part 1 - The Basics'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-9180116076534363955</id><published>2008-11-22T22:29:00.013Z</published><updated>2010-03-02T13:24:10.615Z</updated><title type='text'>Ruby File Access</title><content type='html'>&lt;strong&gt;Reading Files&lt;/strong&gt;&lt;br /&gt;Note that while Ruby accepts backslashes, it seems to prefer forward slashes in file paths, even on Windows.&lt;br /&gt;&lt;br /&gt;You can access the contents of a file like this:&lt;br /&gt;&lt;pre&gt;file = File.open(filename, 'r')&lt;br /&gt;do_stuff_with file&lt;br /&gt;file.close&lt;/pre&gt;&lt;br /&gt;To test if the end of the file has been reached, use &lt;code&gt;file.eof?&lt;/code&gt;. To test if a file has been closed, use &lt;code&gt;file.closed?&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;You can read the entire contents of file in a block:&lt;br /&gt;&lt;pre&gt;contents = File.open(filename, 'r') { |file| file.read }&lt;/pre&gt;&lt;br /&gt;Or just:&lt;br /&gt;&lt;pre&gt;contents = File.open('test.txt', 'r').read&lt;/pre&gt;&lt;br /&gt;If you prefer, you can put each line of the file into an array:&lt;br /&gt;&lt;pre&gt;lines = []&lt;br /&gt;File.open(filename, 'rb') { |file|&lt;br /&gt;file.each_line { |line|&lt;br /&gt; lines &amp;lt;&amp;lt; line&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Note that file here is exactly the same object as in the very first example. The big advantage of using it in a block is that Ruby will ensure the file is closed for you. You can use &lt;code&gt;each_byte&lt;/code&gt; to iterate through the bytes (or, of course, your custom &lt;code&gt;do_stuff_with file&lt;/code&gt; method). You can break lines at any character, for example, at the full stops:&lt;br /&gt;&lt;pre&gt;lines = []&lt;br /&gt;File.open(filename, 'rb') { |file|&lt;br /&gt;file.each_line('.') { |line|&lt;br /&gt; lines &amp;lt;&amp;lt; line&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Alternatively, use &lt;code&gt;IO.foreach&lt;/code&gt;:&lt;br /&gt;&lt;pre&gt;lines = []&lt;br /&gt;IO.foreach(filename, '.') { |line|&lt;br /&gt;lines &amp;lt;&amp;lt; line&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Or simply use &lt;code&gt;IO.readlines&lt;/code&gt; (why was it not named read_lines?):&lt;br /&gt;&lt;pre&gt;lines = IO.readlines(filename, '.')&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Writing Files&lt;/strong&gt;&lt;br /&gt;To write data to a file, you can do something like this:&lt;br /&gt;&lt;pre&gt;file = File.new("test.txt", "w")&lt;br /&gt;file.syswrite("First line of text")&lt;br /&gt;file.syswrite("Second line of text")&lt;br /&gt;file.close&lt;/pre&gt;&lt;br /&gt;However, the prefered way, as with reading a file, is to do it in a block, and leave it to Ruby to close the file:&lt;br /&gt;&lt;pre&gt;File.open("test.txt", "w") { |file|&lt;br /&gt;file.syswrite("First line of text")&lt;br /&gt;file.syswrite("Second line of text")&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;As well as syswrite, you can also use write, print, puts (adds a return at the end of the line), p (alias for puts) and printf (formated print, just like the C function of the same name). Or you can use the append function:&lt;br /&gt;&lt;pre&gt;File.open("test.txt", "w") { |file|&lt;br /&gt;file &amp;lt;&amp;lt; "First line of text"&lt;br /&gt;file &amp;lt;&amp;lt; "Second line of text"&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Binary Files&lt;/strong&gt;&lt;br /&gt;Binaries files are just the same; you just add a b to the second parameter of the open method. This example reads the contents of a binary file to contents (which is a string, by the way), and then writes that to a new binary file:&lt;br /&gt;&lt;pre&gt;contents = File.open(in_filename, 'rb').read&lt;br /&gt;&lt;br /&gt;File.open(out_filename, 'wb') { |file|&lt;br /&gt;file &amp;lt;&amp;lt; contents&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;Manipulating Files&lt;/strong&gt;&lt;br /&gt;These are all pretty self-explanatory:&lt;br /&gt;&lt;pre&gt;File.rename(old_filename, new_filename)&lt;br /&gt;File.exists?(filename)&lt;br /&gt;File.file?(filename)&lt;br /&gt;File.delete(filename)&lt;br /&gt;File.directory?(filename)&lt;br /&gt;File.executable?(filename)  # Returns true for a text file!&lt;br /&gt;File.readable?(filename)&lt;br /&gt;File.writable?(filename)&lt;br /&gt;File.zero?(filename)&lt;br /&gt;File.size(filename)   # Return 0 if the size is zero&lt;br /&gt;File.size?(filename)   # Returns nil if the size is zero&lt;br /&gt;File.ftype(filename)&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;Using Directories&lt;/strong&gt;&lt;br /&gt;You can list the contents of a directory at least three way:&lt;br /&gt;&lt;pre&gt;Dir.entries(dir)  # Surprisingly, no default for current directory&lt;br /&gt;Dir["#{dir}/*.txt"] #&lt;br /&gt;`dir`&lt;/pre&gt;&lt;br /&gt;The first and second will produce arrays of the files in the given folders. The first has just the filenames, and starts with entries for "." and "..". The second has the full path for each file, but does have the facility to filter (as in the example, only .txt files will be listed). The third uses a backquoted string to invoke a system command, and will produce a flat string with the same contents that you would see if you typed "dir" at the command prompt (presumably an error on some operating systems).&lt;br /&gt;&lt;br /&gt;Other methods:&lt;br /&gt;&lt;pre&gt;Dir.pwd                  # Gets the current directory&lt;br /&gt;Dir.chdir('c:')          # Changes the current directory (to c:)&lt;br /&gt;Dir.mkdir('newfolder')   # Create a new directory&lt;br /&gt;Dir.delete('newfolder')  # Or unlink or rmdir&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Putting It Together&lt;/strong&gt;&lt;br /&gt;Here is an actual program. It uses the directory functionality to create an array of file names conforming to the filter (in this case, files end .nif; NetImmersion format), then iterates through the array. For each filename, the file is opened in binary format, the contents read to a string, and then each occurance of one set of strings replaced by another (this was &lt;code&gt;subst&lt;/code&gt;, an array of hashes, giving replacement names for texture files). Finally, the file is saved, again in binary format, with a new filename.&lt;br /&gt;&lt;pre&gt;files = Dir["#{mesh_dir}/in_r*.nif"]&lt;br /&gt;print "Found #{files.length} files.\n"&lt;br /&gt;Dir.chdir(mesh_dir)&lt;br /&gt;files.each { |f|&lt;br /&gt;contents = File.open(f, 'rb').read&lt;br /&gt;subst.each { |h|&lt;br /&gt; contents.gsub!(h[:old], h[:new])&lt;br /&gt;}&lt;br /&gt;File.open(f.gsub(/In_R/i, 'And'), 'wb') { |file|&lt;br /&gt; file &amp;lt;&amp;lt; contents&lt;br /&gt;}&lt;br /&gt;print '.'&lt;br /&gt;}&lt;br /&gt;print "\nDone.\n"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;File data in with code?&lt;/strong&gt;&lt;br /&gt;If you put &lt;code&gt;__END__&lt;/code&gt; in your code, Ruby execution will terminate at that point. Everything beyond that will be considered data, and can be accessed as a file, &lt;code&gt;DATA&lt;/code&gt;. Here is a complete program to illustrate that:&lt;br /&gt;&lt;pre&gt;p DATA.read&lt;br /&gt;&lt;br /&gt;__END__&lt;br /&gt;&lt;br /&gt;Your data goes here&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Reading a CSV file&lt;/strong&gt;&lt;br /&gt;This is trivial, as Ruby provides a library to do just this.&lt;br /&gt;&lt;pre&gt;require "csv"&lt;br /&gt;values = CSV.read "C:/my-data.csv"&lt;/pre&gt;&lt;br /&gt;This gives you your data in a two dimensional array.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-9180116076534363955?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/9180116076534363955/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=9180116076534363955' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9180116076534363955'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9180116076534363955'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/11/ruby-file-access.html' title='Ruby File Access'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-8438880441809914381</id><published>2008-11-15T10:40:00.047Z</published><updated>2010-11-06T14:02:03.139Z</updated><title type='text'>Contents Page</title><content type='html'>This is not a blog in the true sense, where I create a new post each time I learn something. Instead, I am collecting what I learn into a collection of larger posts, and updating those posts as I learn more. Below is a list (a contents page if you like) of posts to date (22/Dec/09) grouped by topic, rather than chronologically, for easy reference.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Ruby Basics&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/03/constants.html"&gt;Constants&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/03/variables.html"&gt;Variables&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/11/conditional-statements.html"&gt;Conditional statements&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/10/case-statement-and-relationship.html"&gt;Case statements and relationship operator&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/11/loops.html"&gt;Loops&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/05/regular-expressions-in-ruby.html"&gt;Regular Expressions&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/01/exception-handling.html"&gt;Exception Handling&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Methods, classes, etc.&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/12/ruby-classes.html"&gt;Ruby Classes&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/10/duck-typing.html"&gt;Duck-typing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/12/ruby-methods-part-1-basics.html"&gt;Methods - Basics&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/12/ruby-methods-part-2.html"&gt;Methods - Not Overloading&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/dynamic-methods.html"&gt;Methods - method_missing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/01/ruby-methods-part-4-calling-methods.html"&gt;Methods - calling&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/02/modules.html"&gt;Modules&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/02/singleton-in-ruby.html"&gt;Singletons&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/02/ruby-proc.html"&gt;Proc objects&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/03/ruby-blocks.html"&gt;Blocks&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/03/accessors.html"&gt;Accessors&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/04/operator-overloading.html"&gt;Operator Overloading&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The Ruby Library (excluding Rails)&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/09/hashes-and-arrays.html"&gt;Hashes&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/11/ruby-arrays.html"&gt;Arrays&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/ruby-strings.html"&gt;Strings&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/11/ruby-file-access.html"&gt;File Access&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/03/ruby-dates-and-times.html"&gt;Time, Date and DateTime&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/05/ruby-unit-testing.html"&gt;Unit Testing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/10/yaml.html"&gt;YAML&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/04/xml-and-ruby.html"&gt;REXML for XML&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/03/ruby-sockets.html"&gt;Sockets&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/09/ruby-gui.html"&gt;GUI with Shoes&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/11/monkeybars-ui-framework.html"&gt;GUI with Monkeybars (and Swing)&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Miscellaneous&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/06/jruby-and-java.html"&gt;JRuby and Java&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Links to APIs&lt;/em&gt;&lt;br /&gt;Because I am always refering to these three...&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/Array.html"&gt;Array&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/String.html"&gt;String&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/Hash.html"&gt;Hash&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Rails&lt;/strong&gt;&lt;br /&gt;&lt;em&gt;Building a Project&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/building-basic-project.html"&gt;Basic Project&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/10/deploying-ruby-on-rails-application.html"&gt;Deploying on Tomcat&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The Model&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/model-part-1.html"&gt;Creation&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/model-part-2.html"&gt;Validation and Association&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/08/model-part-three-sti-and-ire.html"&gt;Interactive Rails Environment&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/08/model-part-4-testing.html"&gt;Testing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/03/model-part-4-find-other-activerecord.html"&gt;Find and other methods&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/05/date-and-time-in-rails-rails-adds-some.html"&gt;Date and Time&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/09/gotchas-for-models.html"&gt;Gotchas&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The Controller&lt;br /&gt;&lt;/em&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/controller-part-1.html"&gt;Routing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/controller-part-2.html"&gt;Basic Methods&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/controller-part-3.html"&gt;Render and Filter&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/11/controller-part-4-functional-testing.html"&gt;Functional Testing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/04/testing-for-valid-html.html"&gt;Testing for valid HTML&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;The View&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/08/view-in-rails.html"&gt;ERB and Links&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/10/view-part-2-scope-helpers-and-partials.html"&gt;Scope, Helpers and Partials&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/01/view-part-2-using-forms.html"&gt;Using Forms&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/01/viw-part-4-using-select-in-forms.html"&gt;Using Select/Options&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/05/using-partials-as-methods.html"&gt;Partials as methods&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Handling Images On Rails&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/08/dynamic-images-on-rails.html"&gt;Dynamic Images with RMagick&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/06/creating-images-for-rails-with-java.html"&gt;Dynamic Images with Java&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/06/displaying-trends-on-graph-image.html"&gt;Generating Line Graphs with Java&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/10/filecolumn.html"&gt;Uploadable Images with File Column&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;More On Rails&lt;/em&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/12/integration-testing.html"&gt;Integration Testing&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/01/rails-mailer.html"&gt;Rails Mailer&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/06/displaying-usage-statistics-on-bar.html"&gt;Usage Statistics on a Bar Graph with HTML&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2008/10/single-table-inheritance.html"&gt;Single Table Inheritance&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/02/moving-to-rails-222.html"&gt;Moving to Rails 2.2.2&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/05/moving-to-rails-238.html"&gt;Moving to Rails 2.3.8&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/04/using-javascript-with-ruby-on-rails.html"&gt;Using JavaScript&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/01/using-java-applets.html"&gt;Using Java applets&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/12/using-sub-directories-in-rails-projects.html"&gt;Organising in Subdirectories&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2009/12/namedscope-in-rails.html"&gt;named_scope&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/06/iterating-through-records-occasionally.html"&gt;Iterating through records&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/03/rails-singularize-and-pluralize.html"&gt;Singularize and Pluralize&lt;/a&gt;&lt;br /&gt;&lt;a href="http://strugglingwithruby.blogspot.com/2010/03/capturing-file-uploads.html"&gt;Capturing file uploads&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Useful Links&lt;/strong&gt;&lt;br /&gt;&lt;em&gt;General Ruby and Rails&lt;/em&gt;&lt;br /&gt;Good Rails tutorial that go beyond the very basic:&lt;br /&gt;&lt;a href="http://www.akitaonrails.com/2008/5/25/rolling-with-rails-2-1-the-first-full-tutorial-part-1"&gt;http://www.akitaonrails.com/2008/5/25/rolling-with-rails-2-1-the-first-full-tutorial-part-1&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Book on Ruby (not Rails):&lt;br /&gt;&lt;a href="http://ruby.activeventure.com/programmingruby/book/index.html"&gt;http://ruby.activeventure.com/programmingruby/book/index.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;FAQ&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/docs/ruby-doc-bundle/FAQ/FAQ.html"&gt;http://www.ruby-doc.org/docs/ruby-doc-bundle/FAQ/FAQ.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Cheatsheet:&lt;br /&gt;&lt;a href="http://www.ilovejackdaniels.com/cheat-sheets/ruby-on-rails-cheat-sheet/"&gt;http://www.ilovejackdaniels.com/cheat-sheets/ruby-on-rails-cheat-sheet/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Quick ref:&lt;br /&gt;&lt;a href="http://www.zenspider.com/Languages/Ruby/QuickRef.html"&gt;http://www.zenspider.com/Languages/Ruby/QuickRef.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Others&lt;/em&gt;&lt;br /&gt;PDF generation:&lt;br /&gt;&lt;a href="http://prawn.majesticseacreature.com/"&gt;http://prawn.majesticseacreature.com/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;XML handling with REXML&lt;br /&gt;&lt;a href="http://www.germane-software.com/software/rexml/docs/tutorial.html"&gt;http://www.germane-software.com/software/rexml/docs/tutorial.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.developer.com/lang/article.php/3672621"&gt;http://www.developer.com/lang/article.php/3672621&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-8438880441809914381?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/8438880441809914381/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=8438880441809914381' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8438880441809914381'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8438880441809914381'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/11/contents-page.html' title='Contents Page'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-9111253578963475189</id><published>2008-11-15T09:20:00.009Z</published><updated>2010-01-06T10:05:51.448Z</updated><title type='text'>The Controller Part 4 - Functional Testing</title><content type='html'>Functional testing targets individual methods in your controllers. It tests the user is redirected, gets the right HTTP response and so on, without actually generating any web pages (though it does generate the HTML so will find errors there).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Setting it up&lt;/strong&gt;&lt;br /&gt;Rails creates functional tests, but there are a few things to be done first... The test database must be set up (though this was probably done when you did your unit testing):&lt;br /&gt;&lt;pre&gt;rake db:test:prepare&lt;/pre&gt;&lt;br /&gt;As with unit testing the require needs altering, if you are using NetBeans 6.1: &lt;code&gt;require 'test_helper'&lt;/code&gt; becomes &lt;code&gt;require 'test/test_helper'&lt;/code&gt;. You should now be able to run the default tests put there by Rails (depending on the changes you have made to the controller and model). Outside of an IDE, the easiest way is using rake.&lt;br /&gt;&lt;pre&gt;rake test (run all tests)&lt;br /&gt;rake test:functionals (run all functional tests)&lt;br /&gt;rake test:recent (run all test files modified in last 10 minutes)&lt;/pre&gt;&lt;br /&gt;There are typically three parts to a test method. The first part is setting up, and might include, for instance, logging a user on. The second, and only required, part calls the method and checks changes to the database. The third part checks the HTTP result.&lt;br /&gt;&lt;pre&gt;def test_should_get_new&lt;br /&gt; login&lt;br /&gt; get :new&lt;br /&gt; assert_response :success&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;Method Calls&lt;/strong&gt;&lt;br /&gt;By default, controller method calls have all the parameters you would expect (eg :controller), but often you want to add more. In this example, an extra parameter is given. This is equivalent to &lt;code&gt;?run=199&lt;/code&gt; at the end of the URL.&lt;br /&gt;&lt;pre&gt;get :new, :run =&gt; '199'&lt;/pre&gt;In his example, parameters for a model are given. This is equivalent to data in a form, as usually accessed via params. I found that this was essential for create, otherwise there is no data in your model, and so nothing gets saved and the test fails.&lt;br /&gt;&lt;pre&gt;post :create, :sample =&gt; { :sample_reference =&gt; 'P12345', :sample_type =&gt; 'PP1'}&lt;/pre&gt;&lt;br /&gt;&lt;strong&gt;Checking the results&lt;/strong&gt;&lt;br /&gt;While your view can, of course, access any instance variable in the controller, you do not have direct access to those variables from within your tests. Instead, they can be accessed though the &lt;code&gt;assigns&lt;/code&gt; method. This allows you to test against values.&lt;br /&gt;&lt;pre&gt;assert_not_nil assigns(:samples)&lt;br /&gt;assert_equal 1, assigns(:samples).length&lt;br /&gt;assert_equal 'glc', assigns(:sample).analysis&lt;br /&gt; # Test value of a specific attribute for one record&lt;/pre&gt;To check the returned HTTP code, just use the standard method:&lt;br /&gt;&lt;pre&gt;assert_response :redirect&lt;/pre&gt;Other options are &lt;code&gt;:success&lt;/code&gt;, &lt;code&gt;:missing&lt;/code&gt; and &lt;code&gt;:error&lt;/code&gt;. Not sure why you would test for the last two.&lt;br /&gt;&lt;br /&gt;You can also test the template used. This is for those occasions when you specified a template (like this; &lt;code&gt;render :template =&gt; 'folder/template'&lt;/code&gt;), otherwise the template is nil.&lt;br /&gt;&lt;pre&gt;assert_template 'samples/new'&lt;/pre&gt;&lt;br /&gt;The last check is where the page has been redirected to. You can use the same parameters for assert_redirected_to that you can for redirect_to.&lt;br /&gt;&lt;pre&gt;assert_redirected_to :controller =&gt; 'samples', :action =&gt; 'home'&lt;br /&gt;assert_redirected_to samples_path&lt;br /&gt;assert_redirected_to sample_path(assigns(:sample))&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://api.rubyonrails.com/classes/ActionController/Assertions/ResponseAssertions.html"&gt;http://api.rubyonrails.com/classes/ActionController/Assertions/ResponseAssertions.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;You can also check what has happened to your database table with the &lt;code&gt;assert_difference&lt;/code&gt; method. Wrap this method around your method call, and it will check that the number of records has changed by the appropriate amount. This example checks the number of records for a model called Post has increased by one (the default value) when a new record is created:&lt;br /&gt;&lt;pre&gt;def test_should_create_post&lt;br /&gt; assert_difference('Post.count') do&lt;br /&gt;   post :create, :post =&gt; { }&lt;br /&gt; end&lt;br /&gt; assert_redirected_to post_path(assigns(:post))&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The destroy method needs to check that the number of records has decreased by one, so in that case the method call looks like this:&lt;br /&gt;&lt;pre&gt;    assert_difference('Post.count', -1) do&lt;/pre&gt;&lt;br /&gt;What &lt;code&gt;assert_difference&lt;/code&gt; does is to determine the value of the first parameter (Post.count in the example), then run the block, and then determine the value of the first parameter again. It then compares the value before and after, and checks that difference against the second parameter (which defaults to +1).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Fixtures&lt;/strong&gt;&lt;br /&gt;Fixtures are a way to easily generate example data. You can point your tests to a fixtures file with:&lt;br /&gt;&lt;pre&gt;fixture :my_data&lt;/pre&gt;&lt;br /&gt;By default, rails includes the statement &lt;code&gt;fixture :all&lt;/code&gt; in tester_helper.rb, so all the fixtures get loaded for all your tests.&lt;br /&gt;&lt;br /&gt;Rails will look for test/fixtures/my_data.yml (or test/fixtures/my_data.csv), and use the data in there to create a data structure, my_data (actually, I suspect my_data is a method that returns the data_structure, but the effect is the same), as well as in your database table. Here is an example of a fixtures file, employees.yml.&lt;br /&gt;&lt;pre&gt;:one&lt;br /&gt;name: Fred Smith&lt;br /&gt;&lt;br /&gt;:two&lt;br /&gt;name: Mary Jones&lt;/pre&gt;&lt;br /&gt;You can access specific records from your fixtures using their label. For the employees fixture, to access Fred Smith, use:&lt;br /&gt;&lt;pre&gt;employees(:one)&lt;/pre&gt;&lt;br /&gt;Functional testing gets a &lt;i&gt;little&lt;/i&gt; more complicated once you have a model that belongs_to another (see &lt;a href="http://strugglingwithruby.blogspot.com/2008/07/model-part-2.html"&gt;here&lt;/a&gt; for how to set up the model). Let us suppose the companies.xml fixture file look like this:&lt;br /&gt;&lt;pre&gt;:one&lt;br /&gt;name: The Excellent Software Company&lt;br /&gt;&lt;br /&gt;:two&lt;br /&gt;name: MegaSoft Ltd&lt;/pre&gt;&lt;br /&gt;In the Employees fixture file, employees.yml, you can set up the association for the company very easily. Just add a key named after your associated model, with the value equal to the label you used for your entry (without the colon):&lt;br /&gt;&lt;pre&gt;:one&lt;br /&gt;name: Fred Smith&lt;br /&gt;company: one&lt;br /&gt;&lt;br /&gt;:two&lt;br /&gt;name: Mary Jones&lt;br /&gt;company: one&lt;/pre&gt;&lt;br /&gt;To assign a company to an employee in a test, use something like this:&lt;br /&gt;&lt;pre&gt;post :create, :employee =&gt; {:name =&gt; 'Tom Johnson', :company =&gt; companies(:one) }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Preventing something when testing&lt;/strong&gt;&lt;br /&gt;It may be desirable to prevent some actions happening while testing, for example, confirmation e-mails being sent whenever a new user account is set up. This is easily done by checking ENV['RAILS_ENV'].&lt;br /&gt;&lt;pre&gt;def my_method&lt;br /&gt;return if ENV['RAILS_ENV'] == 'test'   # Do not during testing&lt;br /&gt;do_stuff_only_if_not_in_test_environment&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Obviously this could cause potential problems, as you are specifically not testing some of your code, so use with care!&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing functions that require a logged in user&lt;/strong&gt;&lt;br /&gt;This is what works for me...&lt;br /&gt;&lt;br /&gt;At the start of each relevant method, put in a line like this:&lt;br /&gt;&lt;pre&gt;login_as_admin(@request)&lt;/pre&gt;&lt;br /&gt;In test_helper.rb, define the login method, something like this:&lt;br /&gt;&lt;pre&gt;def login_as_admin(request)&lt;br /&gt; user = User.new&lt;br /&gt; user.login = "tester"&lt;br /&gt; user.email = "tester@domain.com"&lt;br /&gt; user.username = "Test Administrator"&lt;br /&gt; #...&lt;br /&gt; # Set up other details, permissions, etc.&lt;br /&gt; #...&lt;br /&gt; request.session[:user_id] = user.id&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You should also test that a user will get redirected if not logged in (and that a user logged in but with permissions gets redirected too). Here is how:&lt;br /&gt;&lt;pre&gt;def test_should_be_refused_without_login&lt;br /&gt; get :new   # Example method to test&lt;br /&gt; assert_response :redirect&lt;br /&gt; assert_redirected_to :controller =&gt; 'session', :action =&gt; 'new'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Similar methods can be set up for other user roles, to test how the system behaves.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing helper methods&lt;/strong&gt;&lt;br /&gt;You can test your helpers (in application_help.rb) in your functional tests.&lt;br /&gt;&lt;pre&gt;class HelperTest &amp;lt; Test::Unit::TestCase&lt;br /&gt;  include ActionView::Helpers::TextHelper&lt;br /&gt;  include ActionView::Helpers::TagHelper&lt;br /&gt;  include ApplicationHelper&lt;br /&gt;  # include whatever helpers you want to test here, sometimes you'll need&lt;br /&gt;  # to include some of the Rails helpers, as I've done above.&lt;br /&gt;&lt;br /&gt;  def test_some_helper&lt;br /&gt;  end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;However, you do not have access to the usual Rails helpers, and so any of your methods that rely on them are going to generate errors. There may well be a way around that that I have yet to discover, though as some Rails helpers use the context of the web user to determine their behavior (eg, the output of link_to depends on the current web page) there may not.&lt;br /&gt;&lt;br /&gt;Credit: &lt;a href="http://blog.lathi.net/articles/2006/03/31/testing-rails-helpers"&gt;http://blog.lathi.net/articles/2006/03/31/testing-rails-helpers&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing filter methods&lt;/strong&gt;&lt;br /&gt;You can test filter methods via the usual fuctional tests, for example having one test in which a user is signed in, and another in which the user is not. However, I feel it is better to also test the method itself. I would describe that as unit testing, but as your filter may well do a redirect, you will have to test it in your functional tests. This will be a protected, instance method, so can be invoked like this:&lt;br /&gt;&lt;pre&gt;MyModelsController.new.send(:check)&lt;/pre&gt;&lt;br /&gt;However, as far as I can find, there is no way to set the params variable, so you cannot test a filter that, for example checks an id exists (see forum thread &lt;a href="http://railsforum.com/viewtopic.php?pid=87458"&gt;here&lt;/a&gt; for more).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;What to test&lt;/strong&gt;&lt;br /&gt;My opinion is that you need one functional test for each outcome of each action in your controller. If an action can result in either of two pages being rendered, then that action needs two tests (that said, I rarely bother to test for when a save fails). This rule of thumb does rely on you having pretty much nothing in your controller besides setting up the instance variable, and deciding what page to display; all the complicated stuff is in the models, and that is adequately covered in your unit tests.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Things to watch out for&lt;/strong&gt;&lt;br /&gt;If you get a error complaining about a database table or column missing check that the table or column really is there via SQL - have you updated your test tables after modifying them in the development environment? Alternatively, if there is not supposed to be a table or column of that name (eg a subclass in STI or a model you later removed), check the test/fixtures directory; Rails may be trying to put data from here into your old table - just delete the .yml file for an erroneous table, or edit the data to remove references to the erroneous column.&lt;br /&gt;&lt;br /&gt;If you are getting 300 responses when you expect successes, it might be because you need to set up a session with an appropriate user.&lt;br /&gt;&lt;br /&gt;I write tests by copy-and-pasting existing tests. This leaves me liable to having two tests with the same name. Ruby will give no warning about this, but will only perform one of the tests, which can lead to a false sense of security.&lt;br /&gt;&lt;br /&gt;You cannot rely on the values of the id field. In the development database they number sequentially from 1, but in the test database they start at some huge number.&lt;br /&gt;&lt;br /&gt;I had a method that found the most recent entry of a certain type in the database and used that as a template for a new one. This is difficult to test, because all the entries in your fixtures file get created at the same time, so you have no idea which one will be selected as the most recent. Fortunately, in my case I had a reference number for each record and I could use that instead.&lt;br /&gt;&lt;br /&gt;The data in fixture files gets loaded without validation, which is fair enough. However, validation will apply to the method calls in your tests. So if your update test uses update_attributes, and is working with a record that will not validate (perhaps the record has a required field missing, or the same supposedly unique field as another), the result will be that update_attributes will return false, with no clue as to why. It took me about a long time to realise this.&lt;br /&gt;&lt;br /&gt;Similarly, if your create method is failing to increase the count in your database table, it may be because the validation fails.&lt;br /&gt;&lt;br /&gt;Be aware that functional testing will not check any of your links actually go anywhere, or that your web pages make sense.&lt;br /&gt;&lt;br /&gt;I have to say that in setting up functional tests for my project, most of the errors it turned up were down to the testing, rather than real bugs...&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-9111253578963475189?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/9111253578963475189/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=9111253578963475189' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9111253578963475189'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/9111253578963475189'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/11/controller-part-4-functional-testing.html' title='The Controller Part 4 - Functional Testing'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7994723564984985620</id><published>2008-11-02T23:18:00.004Z</published><updated>2010-04-14T14:00:33.705+01:00</updated><title type='text'>Loops</title><content type='html'>Ruby has several options for loops; I will start with &lt;code&gt;for&lt;/code&gt; and &lt;code&gt;each&lt;/code&gt; loops. In practical terms, there is not a lot between for and each besides style, though &lt;code&gt;each&lt;/code&gt; is actually a method call that takes a block, while for seems to be a language feature. They both iterate over a collection, which could be a hash, a string, an array or a range. Let us look at ranges first.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;For and each with ranges&lt;/strong&gt;&lt;br /&gt;Use of a range takes the place of the normal for/next loop. In these examples, 1..10 and 1...11 are &lt;code&gt;Range&lt;/code&gt; objects; the three dots indicates that the end stops before the terminator, two dots indicates it includes the terminator. These three examples will all print out the numbers 1 to 10, illustrating the difference between each and for, and the two and three dots.&lt;br /&gt;&lt;pre&gt;for i in 1..10&lt;br /&gt; do_stuff&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;for i in 1...11&lt;br /&gt; do_stuff&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;(1..11).each do i&lt;br /&gt; do_stuff&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Ruby is perfectly happy with characters and variables in a &lt;code&gt;Range&lt;/code&gt; object, and the next example shows how a range can be assigned to a variable.&lt;br /&gt;&lt;pre&gt;r = 'a'..'z'&lt;br /&gt;for i in r&lt;br /&gt; puts i&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;n = 5&lt;br /&gt;(1..n).each do i&lt;br /&gt; puts i&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;These loops output the &lt;code&gt;Range&lt;/code&gt; object, by the way, and you can test if something is within a range using the &lt;code&gt;member?&lt;/code&gt; method (eg &lt;code&gt;r.member? "c"&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;A quick note about arrays and ranges. I got really confused by putting square brackets around a range. What is [1..5]? This is an array with a single member, and that member is a Range object.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;For and each with arrays, hashes and strings&lt;/strong&gt;&lt;br /&gt;The &lt;code&gt;each&lt;/code&gt; method allows you to iterate over each member of a string, an array or a hash.&lt;br /&gt;&lt;pre&gt;array.each { member do_stuff_with(member) }&lt;br /&gt;array.each do member&lt;br /&gt; do_stuff_with(member)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;For a hash, you pass two values to the block&lt;br /&gt;&lt;pre&gt;hash.each { key, value do_stuff_with(key, value) }&lt;br /&gt;hash.each do key, value&lt;br /&gt; do_stuff_with(key, value)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;You can use the &lt;code&gt;for&lt;/code&gt; feature with hashes and arrays too, for example:&lt;br /&gt;&lt;pre&gt;h = {:a =&gt; 19, :b =&gt; 35, :c =&gt; 3456}&lt;br /&gt;for k, v in h&lt;br /&gt; puts "key=#{k} value=#{v}"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The times method&lt;/strong&gt;&lt;br /&gt;In Ruby everything is an object, and integer objects (of the class &lt;code&gt;Fixnum&lt;/code&gt;) have a method called &lt;code&gt;times&lt;/code&gt;, which, like each, accepts a block, and iterates from zero up to one less that the number. In these examples, the numbers zero to nine are printed.&lt;br /&gt;&lt;pre&gt;10.times { i puts(i) }&lt;br /&gt;&lt;br /&gt;10.times do i&lt;br /&gt; puts i&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;n = 10&lt;br /&gt;n.times { i puts i }&lt;/pre&gt;&lt;br /&gt;Invoking times on a negative number will create a loop with zero iterations!&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The yield feature&lt;/strong&gt;&lt;br /&gt;You can easily define your own methods that work like &lt;code&gt;each&lt;/code&gt; and &lt;code&gt;times&lt;/code&gt;, using the keyword &lt;code&gt;yield&lt;/code&gt;. Say this method is defined in a class, Car:&lt;br /&gt;&lt;pre&gt;def cars&lt;br /&gt; yield "Red car"&lt;br /&gt; yield "Green car"&lt;br /&gt; yield "Blue car"&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The following will then produce a list of cars; red, green and blue.&lt;br /&gt;&lt;pre&gt;m = MyClass.new&lt;br /&gt;m.cars { c puts c }&lt;/pre&gt;&lt;br /&gt;The cars method runs until it hits the &lt;code&gt;yield&lt;/code&gt;, and at that point passes the value back to the calling code, which then processes it as required. Then the loop goes again, and the cars method continues to the next yield stament. The loop iterates until it runs out of &lt;code&gt;yield&lt;/code&gt;s (the cars method will run to the end regardless of any further &lt;code&gt;yield&lt;/code&gt;s in the code).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The while and until loops&lt;/strong&gt;&lt;br /&gt;Ruby also supports &lt;code&gt;while&lt;/code&gt; and &lt;code&gt;until&lt;/code&gt;. The &lt;code&gt;until&lt;/code&gt; loop is just a &lt;code&gt;while not&lt;/code&gt; loop. There appears to be no option to check the conditional after the iteration that I have found.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Infinite loops&lt;/span&gt;&lt;br /&gt;You can also create infinite loops with the &lt;code&gt;loop&lt;/code&gt; method. Hmm, beter make sure there is some way to break out of the loop, which brings us to:&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The break, redo, retry, next and return keywords&lt;/strong&gt;&lt;br /&gt;Ruby also has some interesting keywords to modify loop behaviour. As with C and derivatives, the &lt;code&gt;break&lt;/code&gt; statement drops you out of the current loop. The &lt;code&gt;next&lt;/code&gt; statement replaces continue; it stops the current iteration, moves to the next one, and passes control to the condition at the end of the loop. The &lt;code&gt;retry&lt;/code&gt; statement is similar, but does not move to the next iteration; it repeats the current one. The &lt;code&gt;redo&lt;/code&gt; statement starts the whole loop from the first iteration. There is also a &lt;code&gt;return&lt;/code&gt; statement, which drops you straight out of the entire method (and optionally takes a parameter; a value returned by the method).&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7994723564984985620?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7994723564984985620/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7994723564984985620' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7994723564984985620'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7994723564984985620'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/11/loops.html' title='Loops'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-758596283944053333</id><published>2008-11-01T18:19:00.006Z</published><updated>2009-10-20T13:27:40.871+01:00</updated><title type='text'>Conditional statements</title><content type='html'>Before going any further, try this in the Ruby interactive console:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;puts false or true        # prints false&lt;br /&gt;puts true and false       # prints true&lt;/pre&gt;&lt;br /&gt;Surprisingly, what gets printed is false and true respectively. What is going on? The problem is that and and or do not bind as strongly as the method call. In effect, you are doing this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;(puts false) or true&lt;br /&gt;(puts true) and false&lt;/pre&gt;&lt;br /&gt;Contrast this with &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;&lt;/code&gt;. These bind more tightly than the method call, and so behave as you would expect.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;puts false  true        # prints true&lt;br /&gt;puts true &amp;amp;&amp;amp; false        # prints false&lt;/pre&gt;&lt;br /&gt;More on operator precedence here:&lt;br /&gt;&lt;a href="http://www.techotopia.com/index.php/Ruby_Operator_Precedence"&gt;http://www.techotopia.com/index.php/Ruby_Operator_Precedence&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;if and unless&lt;/strong&gt;&lt;br /&gt;While C and its derivatives have only &lt;code&gt;if (condition) statement;&lt;/code&gt; Ruby supports two conditionals, &lt;code&gt;if&lt;/code&gt; and &lt;code&gt;unless&lt;/code&gt;, each in two formats:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;if condition&lt;br /&gt; statement&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;unless !condition&lt;br /&gt; statement&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;statement if conditional&lt;br /&gt;&lt;br /&gt;statement unless !conditional&lt;/pre&gt;&lt;br /&gt;You can optionally surround your conditional in brackets.&lt;br /&gt;&lt;br /&gt;Ruby uses lazy conditionals. In the following code, if s is nil, Ruby knows that the expression will be false, and so does not test &lt;code&gt;s.length &gt; 10&lt;/code&gt; - which is good, because that would throw an exception. This could, however, be a problem if you are changing the state of something in your condition; it might not change as often as you might imagine.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;if !s.nil? and s.length &gt; 10&lt;br /&gt; puts 'Long string'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Conditional assignments can be done with the &lt;code&gt;||=&lt;/code&gt; operator.&lt;br /&gt;&lt;pre&gt;s ||= "default"&lt;/pre&gt;&lt;br /&gt;The way this works is that nil counts as false, and in effect it say &lt;code&gt;s = s || "default"&lt;/code&gt;. If s is nil or false, then s becomes &lt;code&gt;"default"&lt;/code&gt;, otherwise it keeps its orignal value.&lt;br /&gt;&lt;br /&gt;Ruby also supports the usual tertiary operator:&lt;br /&gt;&lt;pre&gt;x = conditional ? value1 : value2&lt;/pre&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-758596283944053333?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/758596283944053333/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=758596283944053333' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/758596283944053333'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/758596283944053333'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/11/conditional-statements.html' title='Conditional statements'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7336330044552449828</id><published>2008-10-27T20:56:00.012Z</published><updated>2009-02-09T14:07:39.981Z</updated><title type='text'>YAML</title><content type='html'>YAML is a format for structuring data in a file, like XML. Rails uses YAML to configure your databases, but it does so in such a way that you hardly notice. However, YAML is pretty neat, and you could be missing out.&lt;br /&gt;&lt;br /&gt;YAML stands for "Yet Another Markup Language" (&lt;a href="http://www.yaml.org/spec/history/2001-12-10.html"&gt;here&lt;/a&gt;). Or perhaps for "YAML Ain't Markup Language" (&lt;a href="http://www.yaml.org/"&gt;here&lt;/a&gt;). I guess it depends on whether you think it is a markup language or not (actually the latter seems the more common one).&lt;br /&gt;&lt;br /&gt;There are basically two types of data; that which goes into a hash, and that which goes into an array.&lt;br /&gt;&lt;pre&gt;name: value&lt;br /&gt;- value&lt;/pre&gt;&lt;br /&gt;You can combine them to make complex data structures, such as this array of hashes:&lt;br /&gt;&lt;pre&gt;-&lt;br /&gt;  name: Tom&lt;br /&gt;  age: 32&lt;br /&gt;-&lt;br /&gt;  name: Dick&lt;br /&gt;  age: 19&lt;/pre&gt;&lt;br /&gt;And in fact you can also enter arrays and hashes more like Ruby:&lt;br /&gt;&lt;pre&gt;- { name: Tom, age: 32}&lt;br /&gt;- { name: Dick, age: 19}&lt;/pre&gt;&lt;br /&gt;Or as an array of arrays:&lt;br /&gt;&lt;pre&gt;- [Tom, 32]&lt;br /&gt;- [Dick, 19]&lt;/pre&gt;&lt;br /&gt;Comments start with a hash, #, just like Ruby. Ruby/YAML guesses the type from the format. Strings can be surrounded with single-quotes, double-quote (allowing escape sequences) or nothing. Repeated data can be replaced by an "anchor", by labelling the first occurance. Labels begin with an ampersand, and references to the label with an asterix. Use | or &gt; for data that goes on to more than one line. The former preserves line breaks, the latter does not (see the example at the end of the YAML and Ruby section).&lt;br /&gt;&lt;br /&gt;This example show all of these, and uses symbols as the keys, rather than string as above.&lt;br /&gt;&lt;pre&gt;-&lt;br /&gt;  :name: Tom         # A string&lt;br /&gt;  :age: 32           # An integer&lt;br /&gt;  :male: true        # A boolean&lt;br /&gt;  :born: 1972-02-29  # A date&lt;br /&gt;  :address: &amp;amp;add&lt;br /&gt;    213 Main Street&lt;br /&gt;    Big City&lt;br /&gt;    England&lt;br /&gt;  :comment:&lt;br /&gt;    This is a potentially very&lt;br /&gt;    long comment that will be&lt;br /&gt;    just one line long.&lt;br /&gt;-&lt;br /&gt;  :name: Dick&lt;br /&gt;  :age: 19&lt;br /&gt;  :address: *add&lt;br /&gt;  :comment: 'A very short comment'&lt;/pre&gt;&lt;br /&gt;See here for more details:&lt;br /&gt;&lt;a href="http://yaml.org/spec/current.html"&gt;http://yaml.org/spec/current.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;By the way, NetBeans 6.1 flags up strings that go on to multiple lines as errors; this seems to be a bug in NetBeans.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;YAML and Ruby&lt;/strong&gt;&lt;br /&gt;To use the data from your YAML file in a Ruby program, the first step is to load the YAML library:&lt;br /&gt;&lt;pre&gt;require 'yaml'&lt;/pre&gt;&lt;br /&gt;Then load the data:&lt;br /&gt;&lt;pre&gt;config = YAML.load(yaml_string)       # From string&lt;br /&gt;config = YAML.load_file("config.yml") # From file&lt;/pre&gt;&lt;br /&gt;Then you can access to data just as you would any array of hashes (or whatever your data structure):&lt;br /&gt;&lt;pre&gt;x = config[0]['age']    # x -&gt; 32&lt;/pre&gt;&lt;br /&gt;Note that if you want to use symbols as the keys to your hashes the string needs to be prefixed with a colon (as in the examples above).&lt;br /&gt;&lt;br /&gt;Going the other way is nearly as easy:&lt;br /&gt;&lt;pre&gt;yaml_string = config.to_yaml            # To string&lt;br /&gt;File.open('config.yml', 'w') do |out|   # To file&lt;br /&gt;   YAML.dump(config, out)&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Here is an example program that includes the YAML text (as a "here" document), and illustrates how YAML handles text that goes over multiple lines:&lt;br /&gt;&lt;pre&gt;require 'YAML'&lt;br /&gt;&lt;br /&gt;y = &amp;lt;&amp;lt;YAML_TEXT&lt;br /&gt;:first: &gt;&lt;br /&gt;    This is a folded block,&lt;br /&gt;    line breaks are discarded&lt;br /&gt;    for spaces. The line ends&lt;br /&gt;    with a return.&lt;br /&gt;:second: |&lt;br /&gt;    This is a literal block,&lt;br /&gt;    and so the line-breaks&lt;br /&gt;    are preserved. Again the&lt;br /&gt;    line ends with a return&lt;br /&gt;:third:&lt;br /&gt;    This is a folded block&lt;br /&gt;    too, as YAML defaults&lt;br /&gt;    to that. However, this time&lt;br /&gt;    there is no return at the end.&lt;br /&gt;:fourth: And again a folded&lt;br /&gt;         block formated slightly&lt;br /&gt;         differently, with no return&lt;br /&gt;         at the end.&lt;br /&gt;YAML_TEXT&lt;br /&gt;&lt;br /&gt;h = YAML.load(y)&lt;br /&gt;p h[:first]&lt;br /&gt; # =&gt; "This is a folded block, line breaks are discarded for spaces. The line ends with a return.\n"&lt;br /&gt;p h[:second]&lt;br /&gt; # =&gt; "This is a literal block,\nand so the line-breaks\nare preserved. Again the\nline ends with a return\n"&lt;br /&gt;p h[:third]&lt;br /&gt; # =&gt; "This is a folded block too, as YAML defaults to that. However, this time there is no return at the end."&lt;br /&gt;p h[:fourth]&lt;br /&gt; # =&gt; "And again a folded block formated slightly differently, with no return at the end." &lt;/pre&gt;&lt;br /&gt;You can combine several data structures into a single file. Each should start with three dashes on a line on their own to indicate the start of a new document. Use the &lt;code&gt;load_stream&lt;/code&gt; method to open the file. For example:&lt;br /&gt;&lt;pre&gt;  data_doc = YAML::load_stream(File.open('data.yml'))&lt;br /&gt;  NAME_SCHEMAS = data_doc.documents[0]&lt;br /&gt;  DATA_TYPES = data_doc.documents[1]&lt;br /&gt;  CATEGORIES = data_doc.documents[2]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;YAML and Rails&lt;/strong&gt;&lt;br /&gt;You can use a YAML file to kick start your database table in Rails. Rails already uses YAML, so no need for the require. The YAML file goes in the root directory for your web application. &lt;br /&gt;&lt;br /&gt;One way that I have seen is to put the code inside your migration file, and when you migrate, the data goes straight into your table. However, this is a short term solution only. What happens in your production database or for testing? You could clone your database, but the prefered Rail way is to use Rake to generate the database tables, based on what is in db/schema.rb, and that will not have any initialisation data.&lt;br /&gt;&lt;br /&gt;What I have done (and it may not be the best way) is to write setup methods in my models, which can be invoked from a console session. In this example, for a model called Role, defining the roles a user can have&lt;br /&gt;&lt;pre&gt;  def self.setup_roles&lt;br /&gt;    return false unless Role.find(:all).length == 0&lt;br /&gt;    Role.create(:rolename =&gt; 'administrator')&lt;br /&gt;    Role.create(:rolename =&gt; 'manager')&lt;br /&gt;    true&lt;br /&gt;  end&lt;/pre&gt;&lt;br /&gt;Note that the method fitrst tests to see if there are any roles present already, and only adds the default roles if not. In your tests you can invoke the setup method before a test to load in the data, and be sure that it is the same default data as in your development and production databases. &lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7336330044552449828?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7336330044552449828/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7336330044552449828' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7336330044552449828'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7336330044552449828'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/10/yaml.html' title='YAML'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-3372774985010823225</id><published>2008-10-23T22:01:00.003+01:00</published><updated>2009-01-15T21:59:43.743Z</updated><title type='text'>Single Table Inheritance</title><content type='html'>Rails supports Single Table Inheritance (STI). In this pattern, the superclass is the only model with an associated table in the database, and any object of that class and any subclass is stored in that same table. Rails use a special column named "type" which stores the class name (this means that you will have problems if you name a column "type" for any other reason).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;The Models&lt;/strong&gt;&lt;br /&gt;To implement, create the top level object as a model as normal (with generate scaffold works best for me), but include a column called "type" that is a string. You also need to include every column that all your subclasses will use (though you can, of course, add columns later, as normal).&lt;br /&gt;&lt;br /&gt;For each subclass, create a model (again, I recommend generate scaffold). Modify the model so that the class inherits from the desired superclass, and delete the database migration. Migrate the database, and you are pretty much done.&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance"&gt;http://wiki.rubyonrails.org/rails/pages/SingleTableInheritance&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/"&gt;http://www.juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;You can access all the objects in the class hierarchy through the top level class, or a specific class through other classes.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;A &amp;lt; B &amp;lt; C &amp;lt; ActiveRecord::Base&lt;br /&gt;C.find :all # Get all objects in the table, whatever the class&lt;br /&gt;B.find :all # Get objects of type B only (not A)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Your superclass will need all the fields of all the subclasses - otherwise there will be no table column for field. Each subclass needs its own controller and map.resources entry in routes.rb.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Controllers and Views&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;So how does STI affect the controllers and the views?&lt;br /&gt;&lt;br /&gt;Possibly not at all. You can have one controller for each model, all completely independant, all with their own set of views. However, there is a good chance that there will be some overlap. It is quite likely that you will want to use the same "show" view for each model, for example. Let us suppose SubClass is a subclass of SuperClass; the default show method is this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def show&lt;br /&gt;  @sub_class = SubClass.find(params[:id])&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;It is very easy to point the render method to the SuperClass view (remembering to rename the variable to what super_class/show.html.erb is expecting):&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def show&lt;br /&gt;  @super_class = SubClass.find(params[:id])&lt;br /&gt;  render :template =&gt; 'super_class/show'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We can go a step further. If we set up SubClassController to inherit from SuperClassController, we do not need a show method in SubClassController at all; it can all be handled in SuperClassController. This will work without any changes to SuperClassController, but your object will be of the SuperClass type, and you will lose all the benefits of subclassing. It is better to instantiate your object as the subclass:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;def show&lt;br /&gt;  @super_class = eval("#{params[:controller].classify}.find(params[:id])")&lt;br /&gt;  render :template =&gt; 'super_class/show'&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Other methods for the SuperClass (destroy can be used as is):&lt;br /&gt;&lt;pre&gt;def index&lt;br /&gt;  @super_class = eval("#{params[:controller].classify}.find")&lt;br /&gt;  render :template =&gt; 'super_class/index'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def edit&lt;br /&gt;  @super_class = eval("#{params[:controller].classify}.find(params[:id])")&lt;br /&gt;  render :template =&gt; 'super_class/update'&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def create&lt;br /&gt;  @super_class = eval("#{params[:controller].classify}.new(params[:#{params[:controller].singularize}])")&lt;br /&gt;  if @super_class.save&lt;br /&gt;    flash[:notice] = 'Record was successfully created.'&lt;br /&gt;    redirect_to(:controller =&gt; 'super_class' , :action =&gt; 'show')&lt;br /&gt;  else&lt;br /&gt;    render :template =&gt; 'super_class/new'&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def update&lt;br /&gt;  @super_class = eval("#{params[:controller].classify}.find(params[:id])")&lt;br /&gt;  if @super_class.update_attributes(params[params[:controller].singularize.to_sym])&lt;br /&gt;    flash[:notice] = 'Record was successfully updated.'&lt;br /&gt;    redirect_to(:action =&gt; 'show')&lt;br /&gt;  else&lt;br /&gt;    render :action =&gt; 'edit'&lt;br /&gt;  end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;One last point. In your helps, instead of naming a model for the links, use polymorphic, eg, &lt;code&gt;edit_polymorphic_path(super_class)&lt;/code&gt; rather than &lt;code&gt;edit_super_class_path(super_class)&lt;/code&gt;. This will make Rails point to the right controller for your subclass, whatever it might be.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-3372774985010823225?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/3372774985010823225/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=3372774985010823225' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3372774985010823225'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/3372774985010823225'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/10/single-table-inheritance.html' title='Single Table Inheritance'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-1748218377925719766</id><published>2008-10-17T18:42:00.010+01:00</published><updated>2010-05-10T13:57:11.735+01:00</updated><title type='text'>The View Part 2 - Scope and Helpers</title><content type='html'>&lt;strong&gt;Scope&lt;/strong&gt;&lt;br /&gt;There are significant limits to what you can access from a view.&lt;br /&gt;&lt;br /&gt;For local variables, you can only access variables defined in that view (anywhere in the file, not just that section of Ruby). You cannot access local variables in the controller, or in another view (not even in the layout that gets processed with your view).&lt;br /&gt;&lt;br /&gt;You can access instance and class variables in your controller, as long as they have already been defined in the respective method (I guess a new instance is created with each web request). You cannot access instance and class variables that you have defined by calling a method from the view (they will always be null).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Helpers&lt;/strong&gt;&lt;br /&gt;This brings us to helpers. Helpers are methods in modules that you keep mostly hidden out of the way. The idea is to keep as much Ruby code out of the views, so helpers are mainly for use in that context. Helpers are the only methods you can access, other than instance methods for an instance you have access to.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the helper folder&lt;/em&gt;&lt;br /&gt;You can put your helpers in the helper folder. Rails puts in a helper :all directive, which will automatically load any helpers it finds there, as well as creating an ApplicationHelper file, plus a helper file for each controller or scaffold you generate. In this configuration all helpers are available to all views, regardless of what file you put it in.&lt;br /&gt;&lt;br /&gt;Helpers are set up just like any other Ruby method, the only difference being that the file is a module, not a class.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;module ApplicationHelper&lt;br /&gt;def project_name&lt;br /&gt;'My Great Web App'&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The file must be named in the format "&lt;something&gt;_helper.rb", and the module named "&lt;something&gt;Helper".&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the lib folder&lt;/em&gt;&lt;br /&gt;Helpers can go into the lib directory, with a filename of the form &lt;myname&gt;_help.rb. Again, these are modules, not classes, and look just as before. You need to point Rails to the file, with this in the controller:&lt;br /&gt;&lt;code&gt;helper :myfile&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Rails will then look for myfile_helper.rb, which should contain a module MyfileHelper.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the controller&lt;/em&gt;&lt;br /&gt;If you want to be able to access your helper methods in your controller too, your only option is to put them into the controller, and flag them as helpers.&lt;br /&gt;&lt;br /&gt;To be able to access the methods, you need to put them in your controller (or application controller to allow all views and controllers to use them). the methods are set up as normal, but you need a "helper_method" macro at the top to register the specified methods as helpers.&lt;br /&gt;&lt;code&gt;helper_method :myfirstmethod, :mysecondmethod&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;Accessing Rails' helpers&lt;/em&gt;&lt;br /&gt;You can use the helpers in Rails in your own helpers (at least in your helpers folder). For example, the following will set up a quick link to page, using the standard &lt;code&gt;link_to&lt;/code&gt; helper.&lt;br /&gt;&lt;pre&gt;def link_to_log&lt;br /&gt;link_to 'Sample Log', { :action =&gt; 'home', :controller =&gt; 'samples' }, :method =&gt; :get&lt;br /&gt;end&lt;/pre&gt;&lt;/myname&gt;&lt;/something&gt;&lt;/something&gt;As an aside, I once had a method, &lt;code&gt;select_options&lt;/code&gt;, in a controller that was used by several views, and worked fine. I decided it would be better in a helper, and so moved it across. It stopped working, the interpreter complaining there was no such method. Other methods in the helper file worked fine, even in the same view. After some head scratching, I decided that the problem was due to a name conflict; changing the name of the method got it working again. Why would it fail to find the method (as opposed to invoking the other method or complaining about the wrong number of arguments)? I do not know. However, should your view fail to find a helper method, this could be the reason.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;"&gt;Testing Helpers&lt;/span&gt;&lt;br /&gt;&lt;something&gt;&lt;something&gt;&lt;myname&gt;&lt;br /&gt;Naturally you will want to test your helpers. You may be able to do this in your unit tests, but you may require the infrastruction that comes with a functional test - and anyway, helpers are for views/controllers, not models, so it makes more sense here.&lt;br /&gt;&lt;br /&gt;Here are the bare bones of a test file:&lt;br /&gt;&lt;pre&gt;require 'test_helper'&lt;br /&gt;&lt;br /&gt;class AppHelperTest &amp;lt; ActionController::TestCase&lt;br /&gt;tests SampleLog::GlcsController&lt;br /&gt;&lt;br /&gt;include ApplicationHelper&lt;br /&gt;include ActionView::Helpers::UrlHelper&lt;br /&gt;include ActionView::Helpers::TagHelper&lt;br /&gt;&lt;br /&gt;def test_link_code&lt;br /&gt;  # code here&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;Note that it is necessary to specify which controller you are testing. It may not matter; just pick any. To get access to your new methods, include the helper class. To get access to other methods, include them too.  In the above, I wanted access to &lt;code&gt;link_to&lt;/code&gt; in &lt;code&gt;ActionView::Helpers::UrlHelper&lt;/code&gt;, which in turn accessed &lt;code&gt;escape_once&lt;/code&gt; in &lt;code&gt;ActionView::Helpers::TagHelper&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;For more on helpers see also:&lt;br /&gt;&lt;a href="http://api.rubyonrails.com/classes/ActionController/Helpers/ClassMethods.html"&gt;http://api.rubyonrails.com/classes/ActionController/Helpers/ClassMethods.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;Edit: This page originally hada section on partials, however, partials have changed a lot in Rails 2.2.2, and most of it was no longer true. See this page:&lt;/span&gt;&lt;br /&gt;&lt;a style="font-style: italic;" href="http://strugglingwithruby.blogspot.com/2009/02/moving-to-rails-222.html"&gt;http://strugglingwithruby.blogspot.com/2009/02/moving-to-rails-222.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;/myname&gt;&lt;/something&gt;&lt;/something&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-1748218377925719766?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/1748218377925719766/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=1748218377925719766' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1748218377925719766'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/1748218377925719766'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/10/view-part-2-scope-helpers-and-partials.html' title='The View Part 2 - Scope and Helpers'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4036001762898753005</id><published>2008-10-09T21:25:00.005+01:00</published><updated>2010-01-05T11:27:07.520Z</updated><title type='text'>Deploying a Ruby on Rails Application</title><content type='html'>I am in the process of developing a laboratory sample logging application, and before going to far down the road wanted to check it would work in the production environment. For development I am using WEBrick, MySQL and Ruby (1.8.6) with NetBeans (6.1), but the server has PostgreSQL, with Tomcat (which requires JRuby), so there are plenty of potential problems moving from one to the other. If you do not have Ruby installed, you still need to use "jruby " before rake.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Moving to JRuby and PostgreSQL&lt;/strong&gt;&lt;br /&gt;&lt;em&gt;NOTE:&lt;/em&gt; I had a problem moving to JRuby, as I had Ruby installed as well, and I had not realised that "gem install &lt;name&gt;" will install a gem to Ruby, rather than JRuby, and so I had a rather confusing time with gems installed in the wrong place. To install a gem specifcally on JRuby use "&lt;code&gt;jruby -S gem install &lt;name&gt;&lt;/name&gt;&lt;/code&gt;", and to use rake and warble, likewise prefix the command with "&lt;code&gt;jruby -S &lt;/code&gt;" The -S swich tells jruby to use its own version of the binary. See more here:&lt;br /&gt;&lt;a href="http://wiki.jruby.org/wiki/Getting_Started#How_do_I_run_rake.2C_gem.2C_etc"&gt;http://wiki.jruby.org/wiki/Getting_Started#How_do_I_run_rake.2C_gem.2C_etc&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;My first step was to install JRuby 1.1.4 on the server (JRuby already includes Gems), and then Rails (with: "&lt;code&gt;jruby -S gem install rails -y --no-ri&lt;/code&gt;"). All very easy. Then I had to create a database server in PostgreSQL, which I did through the command line:&lt;br /&gt;&lt;code&gt;createdb mydb&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;I created a new project as normal in Rails, and modified the database.yml file to this:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;development:&lt;br /&gt; adapter: jdbcpostgresql&lt;br /&gt; encoding: unicode&lt;br /&gt; database: mydb_development&lt;br /&gt; username: postgres&lt;br /&gt; password:&lt;br /&gt; host: localhost&lt;br /&gt; port: 5432&lt;br /&gt;&lt;br /&gt;test:&lt;br /&gt; adapter: jdbcpostgresql&lt;br /&gt; encoding: unicode&lt;br /&gt; database: mydb_test&lt;br /&gt; host: localhost&lt;br /&gt; username: postgres&lt;br /&gt; password:&lt;br /&gt;&lt;br /&gt;production:&lt;br /&gt; adapter: jdbcpostgresql&lt;br /&gt; encoding: unicode&lt;br /&gt; database: mydb_production&lt;br /&gt; host: localhost&lt;br /&gt; username: postgres&lt;br /&gt; password:&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I chose to use JDBC, if you chose not to, just delete "jdbc" from the above.&lt;br /&gt;&lt;br /&gt;Then I could use rake to create the databases ("&lt;code&gt;jruby -S rake db:create:all&lt;/code&gt;"). Next I copied across the contains of the app and the db/migrate folders from my PC to the server, along with routes.rb (you might want other files from config too) and the stylesheets (I did not copy the tests; there seemed no point). I migrated my databases ("&lt;code&gt;jruby -S rake db:migrate&lt;/code&gt;").&lt;br /&gt;&lt;br /&gt;Then I installed the gem to handle database connections, either one, depending on whether you want to use JDBC or not:&lt;br /&gt;&lt;code&gt;jruby -S gem install postgres-pr&lt;br /&gt;jruby -S gem install activerecord-jdbcpostgresql-adapter&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;At this point I could fire up the server, and check everything was okay (with "&lt;code&gt;jruby script/server&lt;/code&gt;"), or use the interactive environment (with "&lt;code&gt;jruby script/console&lt;/code&gt;").&lt;br /&gt;&lt;br /&gt;So I had transferred to a different computer (though it could as well been the same computer, if I had been willing to install PostgreSQL on it) with a different database and a different Ruby; there were several issues that I have glossed over, but once you know what to do, pretty straightforward. No actual deployment yet though.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Moving to the Production Environment&lt;/strong&gt;&lt;br /&gt;To ensure the production database is used, in config/environment.rb uncomment this line:&lt;br /&gt;&lt;code&gt;ENV['RAILS_ENV'] = 'production'&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;To create the database tables in the production database:&lt;br /&gt;&lt;code&gt;jruby -S rake environment RAILS_ENV=production db:migrate&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Warbler&lt;/strong&gt;&lt;br /&gt;I used Warbler to create a .war file (Warbler replaces GoldSpike). More information from here:&lt;br /&gt;&lt;a href="http://caldersphere.rubyforge.org/warbler/"&gt;http://caldersphere.rubyforge.org/warbler/&lt;/a&gt;&lt;a href="http://wiki.jruby.org/wiki/Warbler"&gt;http://wiki.jruby.org/wiki/Warbler&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Warbler is installed with:&lt;br /&gt;&lt;code&gt;jruby -S gem install warbler&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;By default, Warbler will package Rails, but no other gems. To change that (so the database connections are including), first create a config file using warbler ("&lt;code&gt;warble config&lt;/code&gt;"). This creates a new file in your application config/warbler.rb. Edit the file to include the gems you require, or insert the following code to include all gems:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;# From http://wiki.jruby.org/wiki/Warbler&lt;br /&gt;# Include all gems which are used by the web application&lt;br /&gt;require "#{RAILS_ROOT}/config/boot"&lt;br /&gt;BUILD_GEMS = %w(warbler rake rcov)&lt;br /&gt;for gem in Gem.loaded_specs.values&lt;br /&gt; next if BUILD_GEMS.include?(gem.name)&lt;br /&gt; config.gems[gem.name] = gem.version.version&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;Some other configuration setting can be found in &lt;code&gt;tmp/war/WEB-INF/web.xml&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Now create the .war file with:&lt;br /&gt;&lt;code&gt;warble&lt;/code&gt;&lt;br /&gt;This should give the following output (if it has an mk command, then it is using Ruby rather than JRuby, I think):&lt;br /&gt;&lt;code&gt;jar cf mydb.war -C tmp/war .&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Note that warbler requires access to a Java JDK, so you need that in your path (&lt;code&gt;PATH=C:\Program Files\Java\jdk1.6.0_07\bin;C:\jruby-1.1.4\bin;%path%&lt;/code&gt;).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Moving to Tomcat&lt;/strong&gt;&lt;br /&gt;The .war file can then be dragged to the Tomcat webapps directory. You may need to restart Tomcat, but not necessarily. Tomcat will decompress the .war file and the web application can now be accessed with:&lt;br /&gt;&lt;code&gt;http://&amp;lt;servername&amp;gt;:8080/&amp;lt;app&amp;gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;8080 is the default port for Tomcat. &lt;app&gt;is the project name, which is the folder name for your application.&lt;br /&gt;&lt;br /&gt;To replace an old version in Tomcat, you need to stop Tomcat, delete the directory with your project name (which Tomcat created by decompressing your old .war file), copy across your new .war, and restart Tomcat.&lt;br /&gt;&lt;br /&gt;Overall it probably took me two to three times longer to deploy the application than it did to build the first draft of it, however, now I know what to do, it will be much, much quicker next time!&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;/app&gt;&lt;/name&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4036001762898753005?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4036001762898753005/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4036001762898753005' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4036001762898753005'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4036001762898753005'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/10/deploying-ruby-on-rails-application.html' title='Deploying a Ruby on Rails Application'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-4591730001663242084</id><published>2008-10-03T18:49:00.008+01:00</published><updated>2009-03-19T15:30:42.587Z</updated><title type='text'>file_column</title><content type='html'>file_column is a simple plugin that lets users upload images, which can then be displayed. There are alternatives out there; this was the first I found, but does the job so well I looked no further.&lt;br /&gt;&lt;br /&gt;Download from here:&lt;br /&gt;&lt;a href="http://www.kanthak.net/opensource/file_column/"&gt;http://www.kanthak.net/opensource/file_column/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Install by dumping the files in vendor\plugins inside your project.&lt;br /&gt;&lt;br /&gt;file_column does not work properly with more recent Rails. Modify file_column_help.rb&lt;br /&gt;&lt;pre&gt;url = ""&lt;br /&gt;url &amp;lt;&amp;lt; request.relative_url_root.to_s &amp;lt;&amp;lt; "/"&lt;br /&gt;url &amp;lt;&amp;lt; object.send("#{method}_options")[:base_url] &amp;lt;&amp;lt; "/"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To&lt;br /&gt;&lt;pre&gt;url = "/"&lt;br /&gt;url &amp;lt;&amp;lt; object.send("#{method}_options")[:base_url] &amp;lt;&amp;lt; "/"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;I think it allows for sub-domains and stuff like that, so is unnecessary in most cases. It fails as request (or @request) is nil. Why should that be?&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;For a table called empire, with a column called image:&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the model&lt;/em&gt;, use something like this:&lt;br /&gt;&lt;pre&gt;file_column :image, :magick =&gt; { :geometry =&gt; "200x100&gt;" }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The magic bit uses RMagick to limit the size of the image.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the new view&lt;/em&gt;, use something like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;% form_for(@empire, :html=&gt; {:multipart=&gt;true}) do f %&gt;&lt;br /&gt;&amp;lt;%= file_column_field "empire", "image" %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;em&gt;In the show view&lt;/em&gt;, use something like this:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= unless @empire.image.nil?&lt;br /&gt;image_tag url_for_file_column("empire", "image"), :align=&gt;"right"&lt;br /&gt;end %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This will only display an image if one is entered in the database (though the file might still be missing). Note the align right option; this is not how it is documented; it should be done through a hash called option, but that did not work for me.&lt;br /&gt;&lt;br /&gt;&lt;em&gt;No changes in the controller.&lt;/em&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Update: For Rails 2.2.2&lt;/strong&gt;&lt;br /&gt;Using this in Rails 2.2.2, I also had to make a change in file_column.rb, around line 619:&lt;br /&gt;&lt;pre&gt;my_options = FileColumn::init_options(options,&lt;br /&gt;                              Inflector.underscore(self.name).to_s,&lt;br /&gt;                              attr.to_s)&lt;/pre&gt;&lt;br /&gt;Becomes:&lt;br /&gt;&lt;pre&gt;my_options = FileColumn::init_options(options,&lt;br /&gt;                              ActiveSupport::Inflector.underscore(self.name).to_s,&lt;br /&gt;                              attr.to_s)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Update: Functional Testing&lt;/strong&gt;&lt;br /&gt;I found this quite a problem, with little guidance anywhere on the web as to what I should be doing. However, this is what I got working. The application is for a record of cylinder batches, each batch requiring a scanned certificate in PDF format.&lt;br /&gt;&lt;pre&gt;test "should update cylinder_batch with file" do&lt;br /&gt; login_as 'manager', @request&lt;br /&gt; cb = CylinderBatch.find(:first)&lt;br /&gt; filename = 'LittleBookOfRuby.pdf'&lt;br /&gt; test_file = File.new("#{RAILS_ROOT}/test/fixtures/#{filename}")&lt;br /&gt;&lt;br /&gt; put :update, :id =&gt; cb.id, :cylinder_batch =&gt; { :certificate =&gt; test_file}&lt;br /&gt; assert File.exists? "#{RAILS_ROOT}/test/tmp/file_column/cylinder_batch/certificate/#{cb.id}/#{filename}"&lt;br /&gt; assert_redirected_to cylinder_batch_path(assigns(:cylinder_batch))&lt;br /&gt; cb2 = CylinderBatch.find cb.id&lt;br /&gt; assert_equal "#{RAILS_ROOT}/test/tmp/file_column/cylinder_batch/certificate/#{cb.id}/#{filename}", cb2.certificate&lt;br /&gt;&lt;br /&gt; get :delete_certificate, :id =&gt; cb.id&lt;br /&gt; assert !File.exists?("#{RAILS_ROOT}/test/tmp/file_column/cylinder_batch/certificate/#{cb.id}/#{filename}")&lt;br /&gt; assert_redirected_to cylinder_batch_path(assigns(:cylinder_batch))&lt;br /&gt; cb2 = CylinderBatch.find cb.id&lt;br /&gt; assert_nil cb2.certificate&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;The method is broken into three parts, the first setting up a few things, the second testing the update method with a new file, and the third part testing the delete_certificate method for removing a file. Usually I would only do one controller method per test method, but in this case one method sets up the other, while the other cleans up after the first, so this was more convenient.&lt;br /&gt;&lt;br /&gt;I put a test file in the fixtures folders. This should be of the same type as you expect in your application. I tried using a YAML file, and while file_column would save the file, it did not update the table; I think file_column rejects file types it does not know. Also as a general point, be aware that file_column does not like anything besides letters, digits, underscores and hyphens in filenames.&lt;br /&gt;&lt;br /&gt;In the parameters for the update method, I simply map the file to the appropriate column name. The file object contains the filename as well as the contents, and file_column can sort it all out. I then check that the file exists in the appropriate directory, the database has been updated correctly and the user redirected.&lt;br /&gt;&lt;br /&gt;In the last section, after calling the delete_certificate method in the controller, I just check the file has gone, the database entry is nil and the redirect again. Simple. When you know how.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-4591730001663242084?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/4591730001663242084/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=4591730001663242084' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4591730001663242084'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/4591730001663242084'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/10/filecolumn.html' title='file_column'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5332978761810990651</id><published>2008-09-13T14:10:00.004+01:00</published><updated>2009-01-15T22:01:24.136Z</updated><title type='text'>Ruby GUI</title><content type='html'>I have been looking at how easy it would be to put a GUI front-end on Ruby. Ruby has no native support for a GUI (one place Java and C# really win over Ruby), and while Rails has become the standard for web aplications, there are numerous options for a GUI plug-in.&lt;br /&gt;&lt;br /&gt;I have had a look at Tk, Fox and Swing (for JRuby). Recently, however, I found Ruby Shoes. Shoes is a very simple GUI, but that is part of its appeal. I doubt it has the comprehensive range of widgets that Tk does, for instance, but it can cope with JPEGs, which Tk cannot (as far as I could find). Also Shoes is dead easy to use:. Download. Install. Start the Shoes application, point it at your ruby file (or one of the samples included). Your application is runnning.&lt;br /&gt;&lt;br /&gt;Unlike most other GUI toolkits, Shoes is not just a Ruby front end to an existing kit, which seems to make it feel more Ruby-like.&lt;br /&gt;&lt;br /&gt;However, the big problem with Shoes is that there is no menu support incorporated. See this forum thread for a discussion on that:&lt;br /&gt;&lt;a href="http://www.ruby-forum.com/topic/165398"&gt;http://www.ruby-forum.com/topic/165398&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Find Shoes here:&lt;br /&gt;&lt;a href="http://code.whytheluckystiff.net/shoes/"&gt;http://code.whytheluckystiff.net/shoes/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;My Quick Guide to Shoes&lt;/strong&gt;&lt;br /&gt;&lt;br /&gt;Everything in Shoes goes inside a Shoes.app block (usually, anyway). The simplest Shoes application is therefore&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Shoes.app do&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You can put in some options at this point - in a hash of course.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;Shoes.app :title =&gt; "A Great Application", :width =&gt; 400, :height =&gt; 600, :resizable =&gt; false do&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;As usual, your require statements go at the very top of the file. Inside the Shoes.app block you can place the code that determines the GUI format and your methods.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Widgets are laid out inside either of two layouts, stacks for vertical stacking, and flows for horizonal flowing widgets. They can be nested for complex interfaces.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;flow do&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;stack :margin_left =&gt; 5, :margin_right =&gt; 10, :width =&gt; 1.0, :height =&gt; 200, :scroll =&gt; true do&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Note that the width in the second example is 1.0, i.e., 100%. You can assign the layout to a class variable, and then manipulate it later in a method for dynamic interfaces.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;@gui_completed = stack&lt;br /&gt;@gui_completed.clear&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Flow and stack are not analogous. In the flow layouts, components fill a line, then go on to the next line, while in a stack, it is strickly one above the other. Shoes does not like horizontally scrollbars (neither do I). Sometimes components will stretch to fill the available room, and if they do that for a flow, they end up on the next line, and it looks more like a stack. The solution is to specify widths.&lt;br /&gt;&lt;br /&gt;You can also use absolute positioning with :left and :top.&lt;br /&gt;&lt;br /&gt;The background method set the background. If this is inside a layout, the background for the layout is set. The border method works the same&lt;br /&gt;&lt;br /&gt;&lt;code&gt;background white&lt;br /&gt;background "back.jpg", :height =&gt; 40 # Set the top 40 pixels tan&lt;br /&gt;border blue, :strokewidth =&gt; 5&lt;br /&gt;background "#000".."#FFF", :curve =&gt; 15 # Gradient filled, black at the top&lt;br /&gt;background "#000".."#FFF", :curve =&gt; 15, :angle =&gt; 90 # Gradient rotated 90 degrees anti-clockwise&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You can use :width, :height, :right, :bottom to put different backgrounds along a certain side or corner. The :curve option should give your panel rounded corners, but not if you specify a border (note that the KNS manual says :radius; this is out of date).&lt;br /&gt;&lt;br /&gt;You can manipulate your panels.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;@my_stack.clear&lt;br /&gt;@my_stack.clear { add_new_stuff }&lt;br /&gt;@my_stack.append { add_new_stuff }&lt;br /&gt;@my_stack.prepend { add_new_stuff }&lt;br /&gt;@my_stack.before existing_component { add_new_stuff }&lt;br /&gt;@my_stack.after existing_component { add_new_stuff }&lt;br /&gt;@my_stack.remove existing_component&lt;br /&gt;@my_stack.hide&lt;br /&gt;@my_stack.show&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Text can be done with: banner, title, subtitle, tagline, caption, para, inscription (in descending order of size).&lt;br /&gt;&lt;br /&gt;&lt;code&gt;title 'Here is my Application'&lt;br /&gt;para 'some simple text'&lt;br /&gt;caption "A caption, in red", :margin =&gt; 8&lt;br /&gt;para strong('Some text in bold (like caption)')&lt;br /&gt;para "Some fancy text", :stroke =&gt; red, :fill =&gt; yellow, :font =&gt; "Monospace 12px"&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;As well as accepting a string, these methods will also take arrays. You can use that to put in formatting within a line. In the second example, a link is created (looking as on a web page); click on it and the do_stuff method is invoked.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;para ['Some text with ', strong('this'), ' in bold']&lt;br /&gt;capture 'Please click ', link('here') { do_stuff }, '.' # Square brackets are optional&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Options include strong, em, code, del, ins, link, span, sub, sup. It does not seem to cope well with characters outside the standard ASCII set. You can dynamically change content with the replace method.&lt;br /&gt;&lt;br /&gt;You can change the style of a link (for the whole application).&lt;br /&gt;style(Link, :underline =&gt; false, :stroke =&gt; 'red')&lt;br /&gt;&lt;br /&gt;Text boxes can be done with edit_line or edit_box. The second example has some default text. The block gets invoked each time the text box is used, so @note will always have the text currently in the text box. How easy is that?&lt;br /&gt;&lt;br /&gt;&lt;code&gt;@text1 = edit_line :margin_left =&gt; 10, :width =&gt; 180&lt;br /&gt;@text2 = edit_box "Default text", :width =&gt; 1.0, :height =&gt; 200, :margin_bottom =&gt; 20 do&lt;br /&gt;@note = @text2.text&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Buttons are easy too. When the button is pressed, the code in the block is invoked.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;button("Add", :margin_left =&gt; 5) { add_todo(@add.text); @add.text = '' }&lt;br /&gt;button "Swap" do&lt;br /&gt;swap&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;There are some built in functions for dialog boxes:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;ask("What is your name?")&lt;br /&gt;confirm("Would you like to proceed?")&lt;br /&gt;ask_open_file&lt;br /&gt;ask_save_file&lt;br /&gt;ask_open_folder&lt;br /&gt;ask_save_folder&lt;br /&gt;ask_color("Pick a Color")&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Most components can be moved and resized&lt;br /&gt;&lt;br /&gt;&lt;code&gt;@comp.move(x, y)&lt;br /&gt;@comp.size(w, h)&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You can capture mouse movement like this:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;motion do x, y&lt;br /&gt;@o.move width - x, height - y&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;click do button, x, y&lt;br /&gt;# button is 1for left button, 2 for right&lt;br /&gt;end&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Images are very easy, just use image, with the path to your image (plus style optins as required). Images can be changed on the fly by setting the path attribute (but why not have a replace method like there is for text elements?).&lt;br /&gt;&lt;br /&gt;&lt;code&gt;@little_image = image 'picture.jpg', :width =&gt; 50, :height =&gt; 50&lt;br /&gt;@little_image.path = 'alternative.jpg'&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You can even access the clipboard:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;self.clipboard = ""&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Shoes supports dropdown lists (list_box), checkboxes (check) and radio buttons (radio). see the manual included with the download for details. The big omission is menus, as mentioned earlier, but hopefully this will be rectified by the end of the year.&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://hackety.org/2008/06/12/martinDemellosGooeyChallenge.html"&gt;http://hackety.org/2008/06/12/martinDemellosGooeyChallenge.html&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.infoq.com/news/2007/09/ruby-shoes"&gt;http://www.infoq.com/news/2007/09/ruby-shoes&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5332978761810990651?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5332978761810990651/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5332978761810990651' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5332978761810990651'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5332978761810990651'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/09/ruby-gui.html' title='Ruby GUI'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-8283937914776906134</id><published>2008-09-03T18:13:00.015+01:00</published><updated>2009-12-15T11:32:03.870Z</updated><title type='text'>Ruby Hashes</title><content type='html'>Ruby uses hashes a lot to pass data around, and one reason for that is that they are just so easy to use. A hash is a object that contains a number of name-value pairs; a dictionary. A hash with a single entry is created like this:&lt;br /&gt;&lt;code&gt;h = {name1 =&gt; value1}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;In practice, the name is usually a symbol, and the value often a string, so this would be the usual format:&lt;br /&gt;&lt;code&gt;h = {:name1 =&gt; 'value1'}&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;For multiple entries, separate with commas.&lt;br /&gt;&lt;code&gt;h = { :name1 =&gt; 'value1', :name2 =&gt; 'value2', :name3 =&gt; 'value3' }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;In method calls the curly brackets seem not to be required or even desired. This can make it seem as though the method takes several parameters rather than a single hash; I think that is deliberate.&lt;br /&gt;&lt;br /&gt;New name-value pairs can be added&lt;br /&gt;&lt;pre&gt;h[:newname] = 'new value'&lt;br /&gt;h.store :newname, 'new value'&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Values can be accessed like an array:&lt;br /&gt;&lt;pre&gt;value = h[:name1]&lt;br /&gt;h[:name1] = 'new value'&lt;br /&gt;h[:name1] = nil&lt;/pre&gt;&lt;br /&gt;Some web sites suggest the last of these will delete the entry; not so! To delete, use the &lt;code&gt;delete&lt;/code&gt; method:&lt;br /&gt;&lt;pre&gt;h.delete(:mykey)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;However, accessing the key with the value is not trivial (as far as I can see). Here are two options:&lt;br /&gt;&lt;pre&gt;h.invert[:value1]&lt;br /&gt;h.find{ |k,v| == :value1 }[0]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;To determine if a hash has a certain key, do this:&lt;br /&gt;&lt;pre&gt;h.key? :my_key&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;You can loop through a hash with the each method. This example outputs each name-value pair (I believe the order is arbitrary).&lt;br /&gt;&lt;code&gt;h.each { |x,y| puts "Name #{x} Value #{y}" }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The delete_if method iterates through the hash and removes any entry for which the block evaluates to true. Note that as with the delete_if method in Aaray, this does not conform to the convention of an explanation mark for methoids that change the original.&lt;br /&gt;&lt;br /&gt;Useful article:&lt;br /&gt;&lt;a href="http://www.informit.com/articles/article.aspx?p=26943&amp;amp;seqNum=3"&gt;http://www.informit.com/articles/article.aspx?p=26943&amp;amp;seqNum=3&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;By the way, Rails uses &lt;code&gt;HashWithIndifferentAccess&lt;/code&gt;, which is special as it allows strings and symbols to be used interchangeably as keys when accessing values.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-8283937914776906134?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/8283937914776906134/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=8283937914776906134' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8283937914776906134'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/8283937914776906134'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/09/hashes-and-arrays.html' title='Ruby Hashes'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-6314904817506935629</id><published>2008-08-22T22:29:00.011+01:00</published><updated>2009-06-09T21:40:13.644+01:00</updated><title type='text'>Dynamic Images on Rails</title><content type='html'>You can serve images through a dedicated method (or action) in your controller, but to use the format facility, you need to register the MIME type. A lot of places say to do that in environment.rb, but leave you stranded after that. What is missing is the require you need in there too:&lt;br /&gt;&lt;pre&gt;require 'action_controller/mime_type'&lt;/pre&gt;&lt;br /&gt;However, I now believe they are wrong (or perhaps out-of-date), and the correct place to put them is in (to ensure they work in the interactive environment):&lt;br /&gt;&lt;code&gt;config/initializers/mime_types.rb&lt;/code&gt;&lt;br /&gt;For example:&lt;br /&gt;&lt;pre&gt;Mime::Type.register "image/png", :png&lt;br /&gt;Mime::Type.register "image/gif", :gif&lt;/pre&gt;&lt;br /&gt;In your controller, you can now do this (for the usual post controller example):&lt;br /&gt;&lt;pre&gt;# GET /posts/1&lt;br /&gt;# GET /posts/1.xml&lt;br /&gt;# GET /posts/1.gif&lt;br /&gt;# GET /posts/1.png&lt;br /&gt;def show&lt;br /&gt; @post = Post.find(params[:id])&lt;br /&gt; respond_to do format&lt;br /&gt;   format.html # show.html.erb&lt;br /&gt;   format.xml { render :xml =&gt; @post }&lt;br /&gt;   format.gif { render :text =&gt; @post.get_image_as_gif.to_blob,&lt;br /&gt;            :status =&gt; 200, :content_type =&gt; 'image/gif' }&lt;br /&gt;   format.png { render :text =&gt; @post.get_image_as_png.to_blob,&lt;br /&gt;            :status =&gt; 200, :content_type =&gt; 'image/png' }&lt;br /&gt; end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;This will respond to a request in four ways depending on the extension, serving up an image if it ends .gif or .png. The methods for creating the images go in Post.&lt;br /&gt;&lt;br /&gt;To embed the image in the web page (note that pages can display slightly faster if you give the size and it is good practice to provide some alt text):&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&amp;lt;%= image_tag formatted_post_path(@post, :gif),&lt;br /&gt;        :size =&gt; "250x250", :alt =&gt; "Image title" %&amp;gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using RMagic&lt;/strong&gt;&lt;br /&gt;RMagick is a Ruby interface for ImageMagick, and seems to be the biggest image drawing package for Ruby.&lt;br /&gt;&lt;a href="http://www.imagemagick.org/RMagick/doc/"&gt;http://www.imagemagick.org/RMagick/doc/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Unfortunately, there is no documentation with it about using it with Rails, and precious little elsewhere. There is an example program, axes.rb, so by way of illustration, this is how to convert it for use in Rails.&lt;br /&gt;&lt;br /&gt;1. Move the &lt;code&gt;require 'RMagick'&lt;/code&gt; to the top of the file, as normal.&lt;br /&gt;2. Wrap the program in a method, with &lt;code&gt;def get_image_as_png&lt;/code&gt; (or whatever) at the top, and &lt;code&gt;end&lt;/code&gt; at the bottom.&lt;br /&gt;3. Edit the bottom from this:&lt;br /&gt;&lt;pre&gt;labels.draw(canvas)&lt;br /&gt;#canvas.display&lt;br /&gt;canvas.write("axes.gif")&lt;br /&gt;exit&lt;/pre&gt;&lt;br /&gt;To this:&lt;br /&gt;&lt;pre&gt;labels.draw(canvas)&lt;br /&gt;canvas.format = 'png'&lt;br /&gt;canvas&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;If there is any problem with your code, Rails just refuses to send the image, with no error message anywhere I could find. If there is no image getting through, try using the interactive environment; it will not display images, but it will show the error messages.&lt;br /&gt;&lt;br /&gt;Note that images have to be converted to blobs before sending. I have choosen to do that in the controller's show method above. Also, you do have to inform RMagick of your file format before invoking to_blob (get a "no decode delegate for this image format" error otherwise).&lt;br /&gt;&lt;br /&gt;Some useful pages:&lt;br /&gt;&lt;a href="http://jeremyweiland.com/archives/49"&gt;http://jeremyweiland.com/archives/49&lt;/a&gt;&lt;br /&gt;&lt;a href="http://nubyonrails.com/articles/dynamic-graphics-with-rails-1-2"&gt;http://nubyonrails.com/articles/dynamic-graphics-with-rails-1-2&lt;/a&gt;&lt;br /&gt;&lt;a href="http://macdiggs.com/2007/03/08/rmagickrvg-outputting-an-inline-image/"&gt;http://macdiggs.com/2007/03/08/rmagickrvg-outputting-an-inline-image/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Colour names:&lt;br /&gt;&lt;a href="http://www.imagemagick.org/www/color.html"&gt;http://www.imagemagick.org/www/color.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Using RMagick with FileColumn&lt;/strong&gt;&lt;br /&gt;FileColumn is a plug-in that makes it very easy to allow users to upload images to your site, and then display them. It uses RMagick, but this seems to lead to a name clash. I found it was necessary to use "include Magick" inside any model that I was using RMagick, rather than specifying Magick::Draw, etc., as Rails complained that the latter was un undefined constant in FileColumn otherwise. Strangely this was not the case in the controller.&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Additional: &lt;span style="font-style: italic;"&gt;If you use JRuby, you will need to use Jva to create images, see &lt;/span&gt;&lt;a style="font-style: italic;" href="http://strugglingwithruby.blogspot.com/2009/06/creating-images-for-rails-with-java.html"&gt;here&lt;/a&gt;&lt;span style="font-style: italic;"&gt;. That page also explores in more depth how to access images in your views, relevant to RMagick images as well as Java.&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-6314904817506935629?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/6314904817506935629/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=6314904817506935629' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6314904817506935629'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/6314904817506935629'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/08/dynamic-images-on-rails.html' title='Dynamic Images on Rails'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-863645472656892987</id><published>2008-08-18T22:22:00.009+01:00</published><updated>2009-12-18T11:57:01.596Z</updated><title type='text'>The Model Part 4 - Testing</title><content type='html'>Rails sets up the skeleton for unit testing when it creates a model. The skeleton is all set to run, though it does not actually test anything, with one trivial test case. However, there are a few steps of preparation:&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Set up the "test" database&lt;/strong&gt;&lt;br /&gt;You need to do this whenever you make changes to the database (any time you do a migration basically). There is a rake task that will do this for you:&lt;br /&gt;&lt;code&gt;rake db:test:prepare&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Note: Rake also supports db:test:clone and db:test:clone_structure; what db:test:prepare does is make a good guess as to which of those is best and does that.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Set up the fixtures&lt;/strong&gt;&lt;br /&gt;Rails generates a fixtures file for each model. A fixture is a file containing entries to populate the database before running each test. If you used the references type for any attributes in your model, you will need to have a belongs_to tag in your model, so that Rails will understand these to be &lt;code&gt;my_model_id&lt;/code&gt; rather than &lt;code&gt;my_model&lt;/code&gt;. You will get a SQL error otherwise complaining about an unknown column name.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Correct the require&lt;/strong&gt;&lt;br /&gt;If you are using NetBeans 6.1, you need to modify the require so Rails can find the test_helper file. &lt;code&gt;require 'test_helper'&lt;/code&gt; should be &lt;code&gt;require 'test/test_helper'&lt;/code&gt;. This has been corrected in NetBeans 6.5.&lt;br /&gt;&lt;br /&gt;The default test should now work. In NetBeans you can right click in the file contents (i.e., the right pane), and choose test from the menu to just unit test a single file, or right click the project in the left pane and select test to run all unit tests.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Tests&lt;/strong&gt;&lt;br /&gt;Rails creates one test file for each model. I write one test method to test one use-case of a method, but I usually put in several assertions to check that the state is what I think it is before and after the method call.&lt;br /&gt;&lt;br /&gt;Note that tests are run alphabetically. Also, be warned that if two tests have the same name, only one will be run, and you will receive no warning that one was not.&lt;br /&gt;&lt;br /&gt;I find unit tests often involve significantly more code that the methods they test, and so most of the bugs are in the tests. However, once the bugs are gone, and the tests are passed, you do have a lot more confidence in your code. If you decide to rewrite the code, the tests should still work fine and are an excellent way to test your rewrite.&lt;br /&gt;&lt;br /&gt;There is an issue with how comprehensive testing should be. If you have a method that manipulates a string, should you test if with nil, objects of a variety of other classes, string objects where the class has been modified? In Java or C# most of these are irrelevant.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing Exceptions&lt;/strong&gt;&lt;br /&gt;Use this:&lt;br /&gt;&lt;pre&gt;e = assert_raise(RuntimeError) { my_code_that_raises }&lt;br /&gt;assert_match(/Error message here/i, e.message)&lt;/pre&gt;&lt;br /&gt;From Jason Roelofs here:&lt;br /&gt;&lt;a href="http://groups.google.com/group/ruby-talk-google/browse_thread/thread/1553af54ab8beaf7"&gt;http://groups.google.com/group/ruby-talk-google/browse_thread/thread/1553af54ab8beaf7&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing Helpers&lt;/strong&gt;&lt;br /&gt;Not really models, but they can and should be tested the same. Helpers are modules, so you just need to &lt;code&gt;include&lt;/code&gt; them. Here is how:&lt;br /&gt;&lt;pre&gt;require 'test/test_helper'&lt;br /&gt;&lt;br /&gt;class AppHelperTest &amp;lt; ActiveSupport::TestCase&lt;br /&gt;&lt;br /&gt;include ApplicationHelper&lt;br /&gt;&lt;br /&gt;def test_my_helper_method&lt;br /&gt;end&lt;br /&gt;end&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Testing private and protected methods&lt;/strong&gt;&lt;br /&gt;t is just as important to test these methods, but how do you access them from outside the class? In Ruby it is actually very easy to access private methods using the send method. This will accept your method name (as a symbol), followed by the appropriate arguments. Something like this:&lt;br /&gt;&lt;pre&gt;assert_equal 'My expected result',&lt;br /&gt;  my_model.send(:my_private_method, arg1, arg2)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Tips&lt;/strong&gt;&lt;br /&gt;If you want to test your model with the parameters from a complex form, you can get Rails to build the hash for you. Throw an exception at the start of the controller method that will handle the submitted form, then, in your web browser, submit the form. Rails will hit the exception, and show an error page, which will include the POST data as a Ruby hash. Copy-and-paste into your test. Rails creates a special hash in which symbols and strings are equivalent for keys; chances are you will need to convert the strings to symbols (assuming you are accessing values with symbols).&lt;br /&gt;&lt;br /&gt;There is an excellent series of blog pages on unit testing by Kevin Skoglund that starts here:&lt;br /&gt;&lt;a href="http://www.nullislove.com/2007/11/14/testing-in-rails-part-1-unit-testing-in-ruby/"&gt;http://www.nullislove.com/2007/11/14/testing-in-rails-part-1-unit-testing-in-ruby/&lt;/a&gt;&lt;br /&gt;For easy reference, part ten lists the assertions available here:&lt;br /&gt;&lt;a href="http://www.nullislove.com/2008/02/20/testing-in-rails-part-10-assertions/"&gt;http://www.nullislove.com/2008/02/20/testing-in-rails-part-10-assertions/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-863645472656892987?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/863645472656892987/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=863645472656892987' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/863645472656892987'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/863645472656892987'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/08/model-part-4-testing.html' title='The Model Part 4 - Testing'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-5586754047471025212</id><published>2008-08-13T21:49:00.010+01:00</published><updated>2009-06-19T13:36:33.294+01:00</updated><title type='text'>The Model Part 3 - Interactive Rails Environment</title><content type='html'>&lt;strong&gt;Interactive Rails Environment (IRE)&lt;/strong&gt;&lt;br /&gt;You can test the methods in your model in an Interactive Rails Environment (IRE), just like IRb. Navigate to your project's root directory, and type:&lt;br /&gt;&lt;pre&gt;ruby script/console&lt;/pre&gt;&lt;br /&gt;In this environment you can access all your models, and the development database (the other databases can be accessed by appending "test" or "production" as a parameter to the above).&lt;br /&gt;&lt;br /&gt;When you are in the Rails interactive environment, you can invoke &lt;code&gt;reload!&lt;/code&gt; after modifying your code to get Rails to notice the changes. However, if you have an object on the go, it will lose its methods (at least, all your methods; methods inherited from, say, ActiveRecord::Base will still be there).&lt;br /&gt;&lt;br /&gt;Here is an example session:&lt;br /&gt;&lt;pre&gt;&gt;&gt; p = Post.find :first&lt;br /&gt;=&gt; #&lt;post&gt;&lt;br /&gt;&gt;&gt; p.test&lt;br /&gt;test&lt;br /&gt;=&gt; nil&lt;br /&gt;&gt;&gt; reload!&lt;br /&gt;Reloading...&lt;br /&gt;=&gt; true&lt;br /&gt;&gt;&gt; p.test&lt;br /&gt;NoMethodError: undefined method `test' for #&amp;lt;post:0xafcd578&gt;&lt;br /&gt;from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/attribute_methods.rb:256:in `method_missing'&lt;br /&gt;from (irb):4&lt;br /&gt;&gt;&gt; p = Post.find :first&lt;br /&gt;=&gt; #&amp;lt;post&gt;&lt;br /&gt;&gt;&gt; p.test&lt;br /&gt;test&lt;br /&gt;=&gt; nil&lt;/post&gt;&lt;/pre&gt;&lt;br /&gt;As can be seen above, the solution is to retrieve the object again after reload. The problem seems to be down to versions; the old object is an instance of the old version, which no longer exists.&lt;br /&gt;&lt;br /&gt;See also:&lt;br /&gt;&lt;a href="http://www.spacevatican.org/2008/5/28/reload-me-reload-me-not"&gt;http://www.spacevatican.org/2008/5/28/reload-me-reload-me-not&lt;/a&gt;&lt;br /&gt;&lt;a href="http://rpheath.com/posts/163-rails-tips-and-tricks-part-3"&gt;http://rpheath.com/posts/163-rails-tips-and-tricks-part-3&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-5586754047471025212?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/5586754047471025212/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=5586754047471025212' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5586754047471025212'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/5586754047471025212'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/08/model-part-three-sti-and-ire.html' title='The Model Part 3 - Interactive Rails Environment'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-7186220849549089690</id><published>2008-08-11T20:10:00.006+01:00</published><updated>2009-02-06T16:12:58.201Z</updated><title type='text'>The View Part 1 - ERB and Links</title><content type='html'>Rails uses the Model-View-Controller architecture. I have already discussed the model (&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/model-part-1.html"&gt;here&lt;/a&gt;) and the controller (&lt;a href="http://strugglingwithruby.blogspot.com/2008/07/controller-part-1.html"&gt;here&lt;/a&gt;); today it is the turn of the view.&lt;br /&gt;&lt;br /&gt;The render method usually (depending on the parameters, as discussed with controllers) opens up a file, parses the file through ERB, and sends the result back to the requesting web browser. There really is not much more to it than that. The only complications are HTML and control structures.&lt;br /&gt;&lt;br /&gt;As the web browser is expecting an HTML formatted page, your ERB template must be in HTML. Generally this is split between two files - the layout and the view itself - with the layout having the header and footer (both in the HTML sense, and the generic stuff at the top and bottom of all your pages), and the view having the HTML specific to that view. You really do need a good knowledge of HTML to do anything beyond the basics, but if you can cope with Ruby, HTML is dead easy.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;ERB&lt;br /&gt;&lt;/strong&gt;ERB (embedded Ruby) is a template system built into the Ruby standard library, and used by Rails. It takes a template string, and where it finds certain codes will perform Ruby processing, substituting the output of that with the codes in the template. Here is an example IRb session using ERB:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;require 'ERB'&lt;br /&gt;template = ERB.new 'My template is called &amp;lt;%= @name %&amp;gt;'&lt;br /&gt;@name = 'Fred'&lt;br /&gt;puts template.result(binding)&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The first line points the interpreter to the ERB.rb file (as this is in the standard library, not the core library). The second line creates a new ERB object called template. The last line calls the results method on template. The binding parameter gives the context so the template uses the value of @name from here, rather than some other method.&lt;br /&gt;&lt;br /&gt;ERb supports a number of tags. Your Ruby code should go between the tags.&lt;br /&gt;&lt;br /&gt;&amp;lt;% %&gt; Perform the Ruby code; no output&lt;br /&gt;&amp;lt;%= %&gt; Perform the Ruby code; output the result&lt;br /&gt;&amp;lt;%=h %&gt; Perform the Ruby code; output the HTML escaped result&lt;br /&gt;&amp;lt;%# %&gt; Comment (note that unlike an HTML comment this is not visible to a visitor looking at the HTML source)&lt;br /&gt;&lt;br /&gt;A % at the begining of the line can also be used to indicate that the line is ruby code (escape with %%). This appears to not be used conventionally. Also, &amp;lt;%% or %%&gt; are replaced with &amp;lt;% or %&gt; respectively, presumably to make it easier to write pages about ERb.&lt;br /&gt;&lt;br /&gt;Actually, &lt;code&gt;&amp;lt;%=h some_ruby_code %&gt;&lt;/code&gt; is a bit of a trick. It is actually a method call, for the &lt;code&gt;h&lt;/code&gt; method. It could be written &lt;code&gt;&amp;lt;%= h(some_ruby_code) %&gt;&lt;/code&gt;; it is just the same.&lt;br /&gt;&lt;br /&gt;Reference&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/"&gt;http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;ERB and Rails&lt;/strong&gt;&lt;br /&gt;Rails already includes ERB, so the &lt;code&gt;require 'ERB'&lt;/code&gt; is not required.&lt;br /&gt;&lt;br /&gt;The layout file, pehaps application.html.erb, must include a call to the &lt;code&gt;yield&lt;/code&gt; method, like this:&lt;br /&gt;&lt;code&gt;&lt;%= yield %&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The &lt;code&gt;yield&lt;/code&gt; uses the view file, perhaps edit.html.erb, parsing it with ERB, and inserting the result into layout result.&lt;br /&gt;&lt;br /&gt;All this processing is done in your controller's superclass (&lt;code&gt;ActionController::Base&lt;/code&gt;), so the environment used (the binding) is that of the method in your controller. ERB can access any variables and methods that you can inside that method.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Links&lt;/strong&gt;&lt;br /&gt;&lt;code&gt;ActionController::Base&lt;/code&gt; includes some methods to help with links. The &lt;code&gt;link_to&lt;/code&gt; method will generate the HTML code for a simple link, as in this example:&lt;br /&gt;&lt;pre&gt;&amp;lt;%= link_to 'New post', new_post_path %&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;"New post" is the text that will appear in the link. The method &lt;code&gt;new_post_path&lt;/code&gt; will generate the URL on the fly (and will take into account the current URL; if the web browser is at http://mydomain.com/, your page will require a different URL to http://mydomain.com/posts/index).&lt;br /&gt;&lt;br /&gt;As well as &lt;code&gt;link_to&lt;/code&gt; there are also &lt;code&gt;button_to&lt;/code&gt;, &lt;code&gt;link_to_if&lt;/code&gt; and &lt;code&gt;link_to_unless&lt;/code&gt; methods.&lt;br /&gt;&lt;br /&gt;API for link_to (with links to alternatives)&lt;br /&gt;&lt;a href="http://www.railsapi.org:8100/actionview-helpers-urlhelper-link_to"&gt;http://www.railsapi.org:8100/actionview-helpers-urlhelper-link_to&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-7186220849549089690?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/7186220849549089690/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=7186220849549089690' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7186220849549089690'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/7186220849549089690'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/08/view-in-rails.html' title='The View Part 1 - ERB and Links'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-2714333425620050937</id><published>2008-07-26T16:26:00.017+01:00</published><updated>2009-03-05T15:44:51.190Z</updated><title type='text'>Ruby Strings</title><content type='html'>Java and C# take the view that strings are fundamental to the language and that API users should be able to rely on them doing exactly what is expected, and so the String class is set in stone, and each instance of String is immutable. Ruby takes the other road, allowing the user to do whatever he wants with a string. The Ruby way is certainly more convenient; whether there are security implications I am not sure (though unlike Java and C#, Ruby is not targetted at running within a web page).&lt;br /&gt;&lt;br /&gt;API documentation:&lt;br /&gt;&lt;a href="http://www.ruby-doc.org/core/classes/String.html"&gt;http://www.ruby-doc.org/core/classes/String.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;There are a surprisingly large number of ways of defining a string in Ruby.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Double-quoted:&lt;/b&gt; Uses backslash escapes (like C, etc.), and embedding variables and code with &lt;code&gt;#{some_code}&lt;/code&gt; (use \# for a hash).&lt;br /&gt;&lt;br /&gt;&lt;b&gt;%Q notation:&lt;/b&gt; &lt;code&gt;%Q/My text/&lt;/code&gt; is almost the same as &lt;code&gt;"My text"&lt;/code&gt;, or &lt;code&gt;%Q[My text]&lt;/code&gt; or &lt;code&gt;%Q@My text@&lt;/code&gt; or whatever (not letters or numbers!). You can use a backslash to include your terminating chartacter, eg &lt;code&gt;%Q!This is important\! Really it is.!&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;Single-quoted:&lt;/b&gt; No escapes (except \' for a single quote). Single quoted strings require less processing than double quoted, though I suspect the difference is insignificant.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;%q notation:&lt;/b&gt; &lt;code&gt;%q/My text/&lt;/code&gt; is almost the same as &lt;code&gt;'My text'&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Return&lt;/strong&gt;&lt;br /&gt;If you include a return in your string (i.e., it goes on to multiple lines), that gets converted into a return!&lt;br /&gt;&lt;pre&gt;s = "First&lt;br /&gt;Second"&lt;br /&gt;p s # =&gt; "First\nSecond"&lt;/pre&gt;&lt;br /&gt;On Windows a return is \n (as in Java, and as opposed to C# which defaults to \r\n).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Concatenating and appending&lt;/strong&gt;&lt;br /&gt;Concatenation as in Java and C#&lt;br /&gt;&lt;pre&gt;a = "first string" + " second string"&lt;br /&gt;   # =&gt; a = "first string second string"&lt;br /&gt;a += " third string"&lt;br /&gt;   # =&gt; a = "first string second string third string"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;But with an append method too.&lt;br /&gt;&lt;pre&gt;a &amp;lt;&amp;lt; " third string"&lt;br /&gt;   # =&gt; a = "first string second string third string"&lt;/pre&gt;&lt;br /&gt;This is the more efficient way (+= creates a new string from the two parts).&lt;br /&gt;&lt;br /&gt;Note that using &amp;lt;&amp;lt; to add an integer between 0 and 255 adds the character (this is because Ruby does not have a character type as such).&lt;br /&gt;&lt;pre&gt;a = "hello"&lt;br /&gt;a &amp;lt;&amp;lt; 72 # a is "helloH"&lt;/pre&gt;&lt;br /&gt;Adding other numbers generates an error. This is one place that Java and C# beat Ruby; they can cope with adding numbers (and indeed any class) to a string without an explicit conversion.&lt;br /&gt;&lt;br /&gt;Repetition (how is that useful exactly?)&lt;br /&gt;&lt;pre&gt;a = "repeated " * 4&lt;br /&gt;   # =&gt; "repeated repeated repeated repeated "&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Extracting bits&lt;/strong&gt;&lt;br /&gt;Extract characters as though it is an array&lt;br /&gt;&lt;pre&gt;a[n]     # the nth character (starting from zero)&lt;br /&gt;a[-n]    # the nth character from the end (starting from 1)&lt;br /&gt;a[n..m]  # a substring from n to m (same as a[n,m]&lt;br /&gt;a[n...m] # a substring from n to m-1&lt;br /&gt;a[n]     # The ASCII value of the character&lt;br /&gt;a[n].chr # The actual character&lt;/pre&gt;&lt;br /&gt;Note that a[n..m] is perfectly happy with variable names rather than specific numbers.&lt;br /&gt;&lt;br /&gt;You can also replace chunks in a similar manner.&lt;br /&gt;&lt;pre&gt;s = "Here is short string"&lt;br /&gt;# =&gt; "Here is short string"&lt;br /&gt;s['short'] = 'long'&lt;br /&gt;# =&gt; "long"&lt;br /&gt;s&lt;br /&gt;# =&gt; "Here is long string"&lt;/pre&gt;&lt;br /&gt;It only replaces the first occurance, but can accept regex expressions.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Methods&lt;/strong&gt;&lt;br /&gt;A list of string methods from here:&lt;br /&gt;&lt;a href="http://www.wellho.net/solutions/ruby-string-functions-in-ruby.html"&gt;http://www.wellho.net/solutions/ruby-string-functions-in-ruby.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To change case:&lt;/span&gt;&lt;br /&gt;capitalize - first character to upper, rest to lower&lt;br /&gt;downcase - all to lower caseswapcase - changes the case of all letters&lt;br /&gt;upcase - all to upper case&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To rejustify:&lt;/span&gt;&lt;br /&gt;center - add white space padding to center string&lt;br /&gt;ljust - pads string, left justified&lt;br /&gt;rjust - pads string, right justified&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To trim:&lt;/span&gt;&lt;br /&gt;chop - remove last character&lt;br /&gt;chomp - remove trailing line separators&lt;br /&gt;squeeze - reduces successive equal characters to singles&lt;br /&gt;strip - deletes leading and trailing white space&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To examine:&lt;/span&gt;&lt;br /&gt;count - return a count of matches&lt;br /&gt;empty? - returns true if empty&lt;br /&gt;include? - is a specified target string present in the source?&lt;br /&gt;index - return the position of one string in another&lt;br /&gt;length or size - return the length of a string&lt;br /&gt;rindex - returns the last position of one string in another&lt;br /&gt;slice - returns a partial string&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To encode and alter:&lt;/span&gt;&lt;br /&gt;crypt - password encryption&lt;br /&gt;delete - delete an intersection&lt;br /&gt;dump - adds extra \ characters to escape specials&lt;br /&gt;hex - takes string as hex digits and returns number&lt;br /&gt;next or succ - successive or next string (eg ba -&gt; bb)&lt;br /&gt;oct - take string as octal digits and returns number&lt;br /&gt;replace - replace one string with another&lt;br /&gt;reverse - turns the string around&lt;br /&gt;slice! - DELETES a partial string and returns the part deleted&lt;br /&gt;split - returns an array of partial strings exploded at separator (eg, s.split(/_/) )&lt;br /&gt;sum - returns a checksum of the string&lt;br /&gt;to_f and to_i - return string converted to float and integer&lt;br /&gt;tr - to map all occurrences of specified char(s) to other char(s)&lt;br /&gt;tr_s - as tr, then squeeze out resultant duplicates&lt;br /&gt;unpack - to extract from a string into an array using a template&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style: italic;"&gt;To iterate:&lt;/span&gt;&lt;br /&gt;each - process each character in turn&lt;br /&gt;each_line - process each line in a string&lt;br /&gt;each_byte - process each byte in turn&lt;br /&gt;upto - iterate through successive strings (see "next" above)&lt;br /&gt;&lt;br /&gt;One that I find partuicularly useful is split, which will break a string into an array of substrings, breaking at the characters you specify (either a string or a regex; defaults to whitespace):&lt;br /&gt;&lt;pre&gt;s = "Here is a\nstring"&lt;br /&gt;# =&gt; "Here is a\nstring"&lt;br /&gt;s.split&lt;br /&gt;# =&gt; ["Here", "is", "a", "string"]&lt;br /&gt;s.split(/a|e|i|o|u/)&lt;br /&gt;# =&gt; ["H", "r", " ", "s ", "\nstr", "ng"]&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Also interesting is scan, which kind of does the opposite of split. Again it returns an array, but this time of the text that matches, rather than the text between the matches. This one example will return an array of links from an HTML document:&lt;br /&gt;&lt;pre&gt;links = content.scan(/&amp;lt;a .+?&amp;lt;\/a&gt;/i)&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;System commands&lt;/strong&gt;&lt;br /&gt;A back quoted string (eg `dir`) gets sent as a command to the OS. The system method in &lt;code&gt;Kernal&lt;/code&gt; does similar (eg, &lt;code&gt;system dir&lt;/code&gt;). You can also use &lt;code&gt;%x[]&lt;/code&gt;, for example, &lt;code&gt;%x[dir]&lt;/code&gt;.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Here Document&lt;/strong&gt;&lt;br /&gt;A "here document" is yet another form of string, designed for large one-off chunks of text (mm, not good for internationalisation). It is denoted by &amp;lt;&amp;lt;, followed by the terminator.&lt;br /&gt;&lt;pre&gt;a = &amp;lt;&amp;lt;END&lt;br /&gt;Some text&lt;br /&gt;END&lt;/pre&gt;&lt;br /&gt;&lt;pre&gt;b = &amp;lt;&amp;lt;-NONSENSE&lt;br /&gt;The hyphen allows the terminator to be indented&lt;br /&gt;NONSENSE&lt;/pre&gt;&lt;br /&gt;&lt;pre&gt;do_stuff(&amp;lt;&amp;lt;TERMI, other_parameters&lt;br /&gt;This text will all&lt;br /&gt;go into the method as the&lt;br /&gt;first parameter&lt;br /&gt;TERMI&lt;/pre&gt;&lt;br /&gt;You can do operations directly on your here document, as shown here:&lt;br /&gt;&lt;pre&gt;p(&amp;lt;&amp;lt;-EOS.reverse)&lt;br /&gt;  This is my string&lt;br /&gt;EOS&lt;br /&gt;# =&gt; "\ngnirts ym si sihT  "&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Formated String&lt;/strong&gt;&lt;br /&gt;You can also generate a formated string with the % operator, which is more or less equivalent to the &lt;code&gt;sprintf&lt;/code&gt; method. One difference is that the % operator requires an array for multiple substitutions.&lt;br /&gt;&lt;pre&gt;"%d" % 12&lt;br /&gt;sprintf "%d", 12&lt;br /&gt;   # =&gt; "12"&lt;br /&gt;"x = %04d, y = %s, z = %.2f" % [12, "value", 1.234]&lt;br /&gt;sprintf "x = %04d, y = %s, z = %.2f", 12, "value", 1.234&lt;br /&gt;   # =&gt; "x = 0012, y = value, z = 1.23"&lt;br /&gt;x = 1.12345&lt;br /&gt;n = 2&lt;br /&gt;"%.#{n}f" % x&lt;br /&gt;sprintf "%.#{n}f", x&lt;br /&gt;   # =&gt; 1.12&lt;/pre&gt;&lt;br /&gt;What is useful about this is that you can pass your format string around, and apply the subsitutions to it multiple times.&lt;br /&gt;&lt;pre&gt;a = "x = %04d, y = %s, z = %.2f"&lt;br /&gt;c = a % [12, "value", 1.234]&lt;br /&gt;   # c is "x = 0012, y = value, z = 1.23"&lt;br /&gt;c = a % [42, "other value", -11.2]&lt;br /&gt;   # now c is "x = 0042, y = other value, z = -11.20"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Templates&lt;/strong&gt;&lt;br /&gt;From here:&lt;br /&gt;&lt;a href="http://freshmeat.net/articles/view/447/"&gt;http://freshmeat.net/articles/view/447/&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;This useful technique will go through the template string, substituting any occurance of something inside :::, with the string in the hash, values, as determined by the names in the hash&lt;br /&gt;&lt;code&gt;templateStr.gsub( /:::(.*?):::/ ) { values[ $1 ].to_str }&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;For more complex template usage, Ruby has ERB (see &lt;a href="http://strugglingwithruby.blogspot.com/2008/08/view-in-rails.html"&gt;here&lt;/a&gt;).&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Other Manipulations&lt;/strong&gt;&lt;br /&gt;Rails offers a variety of new methods for changing strings, including pluralize and tableize; methods used by Rails to convert between table names, class names and filenames.&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html"&gt;http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Here is a way to split camel case into title case:&lt;br /&gt;&lt;pre&gt;"MyCamelCaseClassName".split(/(?=[A-Z])/).join(" ")&lt;br /&gt;   # =&gt; "My Camel Case Class Name"&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Struggling with Ruby: &lt;a href="http://strugglingwithruby.blogspot.com/2008/11/contents-page.html"&gt;Contents Page&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3883020610237687065-2714333425620050937?l=strugglingwithruby.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://strugglingwithruby.blogspot.com/feeds/2714333425620050937/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=3883020610237687065&amp;postID=2714333425620050937' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2714333425620050937'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/3883020610237687065/posts/default/2714333425620050937'/><link rel='alternate' type='text/html' href='http://strugglingwithruby.blogspot.com/2008/07/ruby-strings.html' title='Ruby Strings'/><author><name>F2Andy</name><uri>http://www.blogger.com/profile/14215640430687543082</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-3883020610237687065.post-3060772528329185477</id><published>2008-07-22T21:01:00.011+01:00</published><updated>2010-01-06T12:53:36.102Z</updated><title type='text'>The Controller Part 3 - Render and Filter</title><content type='html'>Ruby on Rails uses the MVC archetecture for web applications. This post is the last of three posts about the controller part, focusing on the rendering and filters.&lt;br /&gt;&lt;br /&gt;&lt;strong&gt;Render&lt;/strong&gt;&lt;br /&gt;The render directive is used to generate a web page, typically a view.&lt;br /&gt;&lt;br /&gt;Render has several options. Render defaults to the view with the method name, in the folder with the name of the current controller, using the layout with the controller name if it exists, or the application layout otherwise. In the &lt;code&gt;Edit&lt;/code&gt; method of &lt;code&gt;PostsController&lt;/code&gt; , these two are equivalent:&lt;br /&gt;&lt;pre&gt;render&lt;br /&gt;render :action =&gt; 'edit', :layout =&gt; 'posts'&lt;/pre&gt;&lt;br /&gt;Indeed, even the word render is unnecessary; Rails will default to the above even if no render directive is present, as seen in the &lt;code&gt;Edit&lt;/code&gt; method of &lt;code&gt;PostsController&lt;/code&gt; (behind the scenes Rails has a variable that notes when a render has been done, to ensure one gets done even if not specified, and to throw an error if you try to do it twice).&lt;br /&gt;&lt;br /&gt;Render has several options.&lt;br /&gt;&lt;pre&gt;:action  # Render using the view app/views/[controller]/[action].html.erb&lt;br /&gt;             # (note that the action named need not exist in any controller)&lt;br /&gt;&lt;br /&gt;:template # As :action, but using the file app/views/[template].html.erb.&lt;br /&gt;         # Use this for consistent views between controllers.&lt;br /&gt;&lt;br /&gt;:file     # Render the giv
