Looking for my family blog?

If you are looking for JeremyandDarcy.com, please click here: http://jeremyanddarcy.com.

Jan 26 10:55

Rounding floats in Ruby

I think it's odd that Ruby doesn't have a way to round to the nearest tenth or hundredth etc. The Float class has a rounding method that rounds to the nearest integer, but I found nothing to round like I needed. I suppose I could use String format, but why should I have to do that when I have no other reason to convert the value to a string? I was feeding RRDTool directly using the Ruby bindings, so I could leave it as a string, but I just didn't like that approach.

After Googling, I noted that some people were extending the Float class with some interesting ideas. However, the most intriguing was a flat out hack. Here it is:

irb(main):001:0> f = 55.34745
=> 55.34745
irb(main):002:0> f.round
=> 55
irb(main):003:0> (f * 10.0).round / 10.0
=> 55.3
irb(main):004:0> (f * 100.0).round / 100.0
=> 55.35
irb(main):005:0>

How about that for a hack? It's simple, but it reminds me of when I'm too lazy to look up the API for the right way to do something and instead write extra code.

Anybody else have good ideas for rounding in Ruby?

Jan 08 17:46

Erasing chips with a pacifier sterilizer

Pacifier Sterilizer

I recently broke out my micrcontroller gear and have been working on a few projects. I have these old 12F671 chips that have an EPROM in them, not EEPROM, but EPROM. They are windowed so you can erase them with UV light before programming them. They are a pain, but I hate to just leave them doing nothing, so I thought I'd find something useful for them to do. I found my old UV chip eraser, but I can't find the 24VDC supply for it! At lunch today I saw our UV germicidal pacifier thingie. And the gears began to turn!

Google tells me that 264nm is the peak wavelength for destroying DNA. So that must be about what the pacifier sterilizer peaks at. Google also told me that to erase EPROMS, you need about 254nm. 10nm isn't very much and most gas tubes like this radiate a wide spectrum. So the output at 254nm I'm sure will suffice.

So into the paci sterilizer went my 12F671's. The sterilizer has a timer, and after one interval I pulled them out, and they still had data, but some of the data was gone! So I sent them in for another round. That did the trick, both chips were blank after two doses. That's at least as fast as I remember it taking my real UV chip eraser! (It's a cheap one I'm sure).

**

I see that http://hackaday.com published this! Thanks guys! Always good to get on one of my favorite websites!

***

I'm also seeing lots of comments about lead exposure. I appreciate everyone's concern, but educate yourself a little before you get too excited. Most of the lead in a chip is in the solder used to bond the leads inside to the silicon wafer. This is sealed inside the chip package, and the lead is in solid form. People get exposed when they A. make the chips or B. melt them down for gold and other precious metals. The chips just don't leech lead like an old tranformer leeching PCBs. You don't get lead exposure handling chips, if you did, we'd all be in bad shape as electronic experimenters.

Finally, the pacifier doesn't touch the inside of the sterilizer they way it's designed. I seriously doubt that the lead can jump from inside the chip to the pacifier in this manner.

Dec 31 17:29

Converting a boolean to a yes or no in Rails

Every once in awhile I run across some syntactical sugar that makes me smile.

I have a boolean in a model for a project at work. I want the users to see a simple yes or no, not a true or false. I've struggled with how to do this in a dry, simple approach and have come up with several ideas. So today I found myself with this problem again, and not liking any of my previous solutions I asked Google for some ideas. I found this bit and put it in the model.

Note sla_flag is the boolean column in the DB.

def sla?
 self.sla_flag ? "Yes" : "No"
end

So now in my views I just reference "sla?".

I love that it doesn't require a multi-line if block. I love that it's a one line method.

I found this nugget here:
http://www.techlists.org/archives/programming/railslist/2006-07/msg03506...

Note the answer is from Yehuda Katz. I saw him at acts_as_conference last year and heard people talking about what an amazing Rubyist he is. When a simple answer like this can teach me so much about Ruby, I have to stop and shake my head. Despite my co-workers high regard for my Ruby skills, I am such a poser next to guys like Yehuda. I'm glad there are guys like him around to learn from!

This solution isn't the most dry, I'd rather make some sort of helper to handle this so that I don't have to do this in every model with a boolean. In spite of this, I have left it in the model. If I put it in a helper I'll never run across it again. So for now it's in plain view in the model to remind me of this syntax for future solutions. During some re-factoring session at a later date I'm sure I'll move it into a generic helper, or explore some of these ideas people have of extending the True class.

May 07 11:52

Alpha Pagination in Rails

One the first cool tricks probably everyone learns when learning Ruby are the range tricks.

(0..5).to_a #=> [0, 1, 2, 3, 4, 5]
(0...5).to_a #=> [0, 1, 2, 3, 4]

So I was looking to "alpha paginate" my user list in a Rails app. It was already paginated (by another team member of mine) with the pagination helper, but that's useless if I wanted to find a user with the last name beginning with L.

I've seen an alpha paginator out there, but I just couldn't help thinking that it was excruciatingly simple to implement my own.

I took a look at the Ruby, Range class, I figured if the Ruby creators were slick enough to give us cool things like (0..5), why not something like ('A'..'Z')? Well, sure enough, it's in there.

http://www.ruby-doc.org/core/classes/Range.html

Have I mentioned how much I love Ruby?

The first thing I did was write a helper method in application_helper.rb so that I could use this anywhere in my Rails app:

def alpha_links(action)
 return_text = '[ '
  ('A'..'Z').to_a.each do |letter|
   return_text = return_text + link_to(
    "#{letter} ", 
    :action => action, 
    :id => letter)
   end    
 return return_text + ' ]'
end

I figured it would be nice to have a single method call that generates all the links, and allows me to set the controller method that's called when a user clicks one of the links.

Then in the view, I added this line:

<%= alpha_links('list') %>

Now on the view I have a nifty block that looks like this:
[ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ]
where each letter is a link to:
/user/list/A or /user/list/B etc etc.

Finally, I modified the "list" controller method as follows:

def list
 if params[:id].nil?
  alpha = 'A%'
 else
  alpha = params[:id] + '%'
 end
 
 @users = User.find(
  :all,
  :order => 'last_name',  
  :conditions => ["last_name like ?", alpha])
 
end

Oops! As DHH used to say. My alpha pagination is done.

Note that ActiveRecord will sanitize the conditions hash in the example above, to avoid SQL inject attacks. It's worth mentioning that if I wrote that line like so:

 :conditions => "last_name like '#{alpha}%'")

ActiveRecord would NOT sanitize it and SQL could very easily be injected right from the URL!

Apr 23 09:32

Lambdas and named_scope

I'm been trying to wrap my head around lambdas. Like with most concepts, I try to educate myself on the subject, then as I'm writing code I try to find ways to employ the concepts to further sink them into my brain. I just haven't been able to do this with lambdas for some reason.

Then, one of my dev team members passed this link to the team to tell us about named_scopes: http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-fi...

Named_scopes are really cool, as a matter of fact, I was already doing something similar, but I was defining a method on the model and putting my custom finder there. Named_scopes just makes for less typing when doing this.

When I saw lambda in the named_scope example, I realized that I'm already using lambdas in my code, I just didn't make the connection between the concept and the application. Probably because in the context I'm employing lambdas, I don't need the lambda keyword.

I love the collect method on the enumerable class, and it turns out, it employs a lambda. Let's say I need an array of the catalog numbers for the line items on an order.

order = Order.find(:first)
catalog_numbers = order.line_items.find(:all).collect 
 { |item| item.cat_no }

I'm passing in the code block:
{ |item| item.cat_no }

to the collect method, and this is the concept of a lambda. You pass a code block into a method like a value.

Another example is the find method on enumerable. Let's say I have an array of hash objects (like what you get with an activerecord collection), and you want to find one of the hash objects (without going to the DB again).

my_item = order.line_items.target.find 
 { |item| item.cat_no == '231-5543' }

Note: if order is an activerecord object, calling the find method will call activerecord's find method. In this case I want enumerable's find method, hence the target method inserted in there. If order was just an array of hash objects, you can omit the 'target' method.

Also note, even with eager loading, calling order.line_items.find would generate another SELECT query. So in order to take advantage of eager loading, I'm using this pattern to pick out a single child.

So, looks like I'm using lambda's already, and didn't realize it.

Jan 30 18:53

acts_as_conference

Wow, it's been since July since I last posted on my blog. That's a cryin' shame. Verizon Business has been keeping me extremely busy, which is good. No time to blog though.

So, the point of this post, I'm attending acts_as_conference in Orlando next weekend. I'm very excited as this will be my first Rails conference!
http://www.actsasconference.com/

As for non-professional projects, HairForecast.com is rolling along, no major news to report on it but I'm pleased that it's visitor rate has been steady, and I'm still getting great fan mail on it a few times per week.

Jul 25 15:14

Shuffling my collection of girls

Yes, this is a dev post, no, it is not a post about my personal life. I'm happily married to only one woman. ;-)

Now that I've clarified that. If you've ever looked at HairForecast.com, you'll note that I have some graphics that depict the weather, and there's a different girl in each graphic. The girls wear coats when it's cold, they have umbrellas when it rains, their hair is blown around when it's windy, etc. You'll also note that I have 3 different girls that I rotate. I wanted to have the girls appear in random order, but never have the same girl appear twice (on the same forecast day).

Jul 10 13:42

Simplifying your test code

Robby, one of the developers I worked along side at BlueSpire, used a pattern in our test suite to simplify the setup of objects under test. I thought it very useful and it made the code so much more readable.

The idea is, when setting up an object n different ways, it's nice to set only the parameters you need on the same line as the instantiation.

Jul 08 22:18

Using method_missing in Ruby

I first learned about method_missing when Christopher Bennage asked me about it. Even after looking it up and explaining it to Christopher, I didn't find any practical use for it in the things I was doing.

At least until tonight, that is.

I've been working on expanding Hair Forecast into Canada. I have the Canadian weather data described in active record like so:

    create_table :canadaforecasts do |t|
      t.column :fcstdate, :date
      t.column :lat, :float
      t.column :lon, :float
    end

Jun 11 21:47

Hello Drupal!

I became frustrated with blogger lastnight. It refused to publish to my server, and didn't throw any errors. I was watching my log files on the server and blogger wasn't even attempting to connect and publish.