Home | Blog Roll |  Link Roll |  Colophon/About| |


Archive for the ‘Ruby and Rails’ Category

The Real Reason for no Increased productivity behind Scripting Languages, reveled.

Thursday, January 31st, 2008

In a lazyweb “fools seldom differ” moment, my post The Real Reason for Increased productivity behind Scripting Languages (commenting on a XKCD comic) has been riffed on by Bart of “Moves on Rails” : The new programmers excuse for slacking of:

compiling_new_style.png.

(no, I’m not doings a “Zed”, now please excuse us while we hide from the //mobs…. ;)

The Real Reason for Increaded productivity behind Scripting Languages!

Wednesday, August 15th, 2007

from

Ruby on Rails link roundup

Monday, July 30th, 2007

Links for the first week on July 07

Saturday, July 7th, 2007

:

Railing :

  • - LinRails : a binary package that includes Ruby-1.8.6, Rubygems-0.9.4, Rails 1.2.3, Mongrel 1.0.1, MySQL-5.0.41, ncurses-5.6, OpenSSL-0.9.8e, and zlib-1.2.3. making it easy to get a Ruby on Rails development environment running in no time.

Web Stuff

Culture

Amazon’s Web Top Site (Alexa) web service and Ruby; Fixed and juiced!

Thursday, March 15th, 2007

I had need to get some data from Amazon Web Services, and in particular their Alexa Top Sites web service which provides access to lists of web sites ordered by Alexa Traffic Rank.

And, happily, they had a Query Example in Ruby! (as well as Java, Perl, PHP, and C#)

It is a bit unclear about where to get the country code’s although I see that you can do a query to get the list using ResponseGroup=ListCountries ( I just cheated and used Alexa site to get the country code I wanted) pasted in the access key and double secret code key and fired it off…

Only it didn’t seem to work! WTF! the error said “The URI http://awis.amazonaws.com/onca/xml is not valid” but but i didn’t change that!!! Carefully reading, and remembering to breathe, the doc’s I noticed that it refereed to the base uri as being “http://ats.amazonaws.com” rather that what was in line 27 of the topsites.rb file : “http://awis.amazonaws.com/onca/xml” , so I tried that and it worked! I guess they changed some stuff and have not updated the sample code? sloppy!

The next issue was that the query only produces a max count of 100 and I wanted thousands! (The Alexa site already shows the top 100 by country.)

I quickly wrote up some ruby code to figure out my start count and generate a filename for each increment which was passed to a modified aws topsite query (changed to write to a file name rather than standard output i.e. the console), and many xml files later I’m done. (now to import the mess! - which proved to be easy to do in excel 2003)

def loopcount(nol)
begincount = 1
incr = 100
for x in 0..nol
start = begincount + (x * incr )
filename = “c://aws/aww_ts_” + x.to_s + “.xml”
QueryAWS_topSite(start, incr, filename)
end

Maybe I will mess with it some more to create one giant xml file (return the xml object and parse out the elements I want before writing to one file?) and otherwise more elegant, but for now it is “good enough”. and geeky fun too!

Amazon Web Services Developer Connection : Query Example in Ruby

Thursday, February 1st, 2007

Amazon Web Services Developer Connection : Query Example in Ruby

line 27 of the sample should read :
http://ats.amazonaws.com?” +

not

http://awis.amazonaws.com/onca/xml?” +

Rails 1.0: Party like it’s one oh oh!

Tuesday, December 13th, 2005

Ruby on Rails Release 1.0 is Out of the Box!, with a re-designed web home @ http://www.rubyonrails.org/, and lots of good stuff to discover. Also on the main page is “Who is already on Rails?” highlighting a few real world applications already using Rails and more applications

you mean it hasn’t been 1.0 before?”

Building a Better Drop Down Selection List for Ruby on Rails

Saturday, December 10th, 2005

In building the View part (using RHTML Templates) of a RoR () application we frequently want to present a controlled set or list of options for the user to select and way to do this is using the html , which is easy enough to do in RoR, either building it with embedded Ruby (ERb) and/or using the select() helper method, and with only a little more effort you can do so using information stored in a database table via your models, of course, using a find() method to get the values. The “Agile Web Development with Rails” AWDR book has some excellent information on doing this (Chapter 17 pages 357 - 359 ).

The collection_select helper adds in some extra sugar automatation dealing with the collection.


<%=
	@items = Item.find(:all, :order => "name")
	collection_select("stuff", "item_id", @items, :id, :name )
%>

However, I find the current ways of doing this lacking in two ways:

  1. The element present to the users to select are based on the values of only one field. What if you what to be more descriptive and present more information?
  2. The use of the selected=”selected” attribute is necessary when you are editing an existing record - easy, but also for new elements there is no way to present a default element, unless the first element is the default. But what if you what to set Manitoba as the default in a list of provinces (M being in the middle), or present a blank choice or a “Please Select a Widget Type” message?

With this goal in mind I set out to build my more user friendly generated Select.


1   <select id="stuff_item_id" name="stuff[item_id]">
2   <% if @stuff.item_id == 0 or  @stuff.item_id == nil -%>
3     	<option value="" selected="selected" >Please Selected An Item</option>
4   <% end -%>
5   <% @items = Item.find(:all, :order => "name")
6 	 @items.each do |item| %>
7   <option value="<%= item.id %>"
8   <% if @stuff.item_id == item.id -%> selected="selected"<% end -%>
9   >
10 <%= item.name %> (<%= item.description %>)
11 </option>
12 <% end %>
13 </select>

which when used (when doing a “new”) I get something like this:

now for some explaining (assuming some knowledge of ruby and rails):
we are updating a stuff table/model with a field called “item_id”, there is also a table/model call item with fields “id”, “name”, and “description”

  • line 1: start the select tag. the name=”stuff[item_id]” is important to populate the “item_id” field in “stuff”
  • lines 2-4: checking the value in for the current record of stuff. When a new record is created it is zero, when it has failed validation it is “nil”. In either case this is where the default message (which might just be an emplty string), and value goes. You could also do a different default with validation fails.
  • line 5: gets all the values from the Item model, sorted by name, and stores it in @items.
  • line 6: start looping thru @items, one item at a time.
  • line 7: builds each option tag of the select and sets the value attribute to “item.id”, which is what will be actually stored in “stuff”.
  • line 8: sets the selected attribute if we are editing an existing “stuff” record.
  • line 9: close the front part of the option tag.
  • line 10: build what the user see, lin this case the name and in brackets the description
  • line 11:then close the option tag for this value of item.
  • line 12: close the looping for this item , which was started on line 6.
  • line 13 :close the select tag.

Hopefully this is clear enough to help others. I’m still exploring the documentation and the RoR api doc has a section on ActionView::Helpers::FormOptionsHelper, with some specialized select Helpers.

I did not address the “Manitoba as the default in a list of provinces (M being in the middle)” objection in the above code. To do so you have have to A) know or figure out that “Manitoba” had a value of 6, then B) , my guess at best - or least worst - practice, do a if @stuff.item_id == 0 then @stuff.item_id = 6 to set this default value before the select.

Perhaps I should I will build a re-useable helper “collection_select_with_defaults”? …very very soon.

Amy Ho has some useful advice in A Little Form Help From Your Friends, all about Rail form helpers

I should also note that similar problems and solutions exist in PHP, JSP and ASP.

update: on the RoR wiki there is HowtoUseFormOptionHelpers

March 7, 2006 Update: , Sam Livingston-Gray not only linked here, but wraped it in a user *and* developer friendly helper function in the comments below

Getting Ruby’s “require” to work in the Poignant Guide to Ruby

Monday, September 12th, 2005

I’m working my way thur “Why’s (Poignant) Guide to Ruby”, chapter 4 “Floating Little Leaves of Code” and ran it a problem doing the “Making the Swap” sub-section example (part of 3. Chaining Delusions Together” - (on a Win XP box, with version 1.8.2 ) - with repect to where the Hash of code words is used in anther program using the require function/method (message).

Although the wordlist.rb loaded (confirmed with more testing), when I went to use the variable defined in it (”code_words”) , I was getting “undefined local variable or method `code_words’ for main:Object (NameError)”. WTF?!!

To simplify, the wordlist.rb was :

code_words = {
'starmonkeys' => 'Phil and Pete, those prickly chancellors of the New Reich',
'catapult' => 'chucky go-go', 'firebomb' => 'Heat-Assisted Living',
'Nigeria' => "Ny and Jerry's Dry Cleaning (with Donuts)",
'Put the kabosh on' => 'Put the cable box on'
}

and, to make it an even simpler example, the calling file (SimReq.rb) could have been:

# SimReq.rb to test require loading
require 'wordlist'
code_words.each {|key, value| print "Key:", key, " for Value:", value,
"\n" }

After a bit of head scratching and hair pulling, I got around the problem by making code_words global with “$” on “code_words” in both files. (i.e. “$code_words“). Which work but was un satisfing. global variable are evil, and messy for any non trivial example.

So was it a scoping problem? Was there a better, or best practice, to do something like this trivial example or is this Chunky Bacon payback for actually doing the example or someother PEBKAC issue?

The anwser was YES.

Posting on the comp.lang.ruby groups (once again exploding my ignorance so you don’t have to) resolved my problem and increased my understanding (oh happy day), to wit :

a) I should be using the fixed version of the Poignant Guide @ http://qa.poignantguide.net/, not the usual url location. (and why isn’t the version @ http://poignantguide.net/ruby/ upto date or redirecting? Health concerns about the colour blue, apparently. So it was only recently caught and is in the process). The fixed version used suggetion b), as well as the load method, rather than require. Is there a differance?

b) Using a Constant is a better practices and in this case the simplest thing that works. So code_words becomes Code_words in both files. (convention is the constants should be all upcase, so it should be CODE_WORDS rather.

c) Making a Class is a best practice especiallyif your doing something more than trivial. to quote:

Local variables used in a file you ‘require’ do not appear in the requirer’s scope. Usually the best thing is to wrap what you need in a class or module: class CodeWords
def initialize
{ 'a' => 'b',
'c' => 'd' }
end
end

then in the requiring file:

require 'codewords'
code_words = CodeWords.new

Also, in the Ruby’s Docs for the load method it notes :

In no circumstance will any local variables in the loaded file be propagated to the loading environment.

.

I just wish it said that under require, or “see load method, wrap=true”. …sigh…Many thanks to David and Dominik, and of cource, why ..and now back to the brain busting.


Close
  • Social Web
  • E-mail
E-mail It