Snippets: Rails validates_format_of

August 31, 2007 @ 12:15 PM | posted by carmelyne

(last updated: 09.01.07)
1
2
3
4
5
6
7
8
# email
validates_format_of :email, :with => /(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i

# url
validates_format_of :url, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix

# password
validates_format_of :password, :with => /^\w+$/ (alphanumeric)

Snippets: Rails yield :header_css

August 31, 2007 @ 12:15 PM | posted by carmelyne

(last updated: 08.31.07)
1
2
<%= stylesheet_tag 'my-site-wide-css' %>
<%= yield(:head_css) || (stylesheet_link_tag 'general_header_css') %>

Restful_authentication & Activation

August 21, 2007 @ 06:06 PM | posted by carmelyne

(last updated: 03.12.08)

Extension of Railscasts Episode 67


============================

Update: [March 12, 2008] This blog post is outdated so if you found this page using google, I'd recommend reading something more up-to-date. Unfortunately, I don't know where else to refer you right now. I shared my thoughts and experience with the plugin at the time I was using it for a project. Living in the now, you can grab Obie's Book "The Rails Way". That comes highly recommended!

============================

Ryan showed us how to set up restful_authentication a plugin by Rick Olson with his 67th Railscasts Episode: restful_authentication. Pretty awesome! Now, we will extend it to the activation part.

./script/generate authenticated user sessions --include-activation

With the added --include-activation option, more files and codes will be generated to handle "Activation for a User who just registered".

Shall we break them down in steps... baby steps and with codes. I would be happy to do a screencast for this but I dont own a podcast mic yet so lets do it the old school way. I know we're all spoiled by Ryan's RailsCasts and Geoffrey's PeepCodes. We are the little Brats! :)

After generating the files for restful_authentication, follow the 67th episode set up plus these...

Step 1: All about Environment.rb

Open your environment.rb file and set up the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# First, specify the Host that we will be using later for user_notifier.rb
HOST = 'http://www.yourrailsapp.com'

# Second, add the :user_observer
Rails::Initializer.run do |config|
  # The user observer goes inside the Rails::Initializer block
  config.active_record.observers = :user_observer
end

# Third, add your SMTP settings
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  :address => "mail.yourrailsapp.com",
  :port => 25,
  :domain => "mail.yourrailsapp.com",
  :user_name => "carmelyne@yourrailsapp.com",
  :password => "yourrailsapp",
  :authentication => :login
}

Note: Just a heads up -- if you're on SliceHost like I am, I can't get this to work on just Postfix on Ubuntu. I needed to set up the SMTP settings on the environment.rb file.

Step 2: All about app/models/user_notifier.rb

Now you can see how we set a dryer way to add the HOST via #{HOST}. The codes below is also an example if you've extended it to handle resetting the passwords. Although you will have to add an additional user migration for "password_reset_code" and adding it to your user model/controller codes and more to your routes....
Anyway, code snippets below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class UserNotifier < ActionMailer::Base
  def signup_notification(user)
    setup_email(user)
    @subject    += 'Please activate your new account'  
    @body[:url]  = "#{HOST}/activate/#{user.activation_code}"
  
  end
  
  def activation(user)
    setup_email(user)
    @subject    += 'Your account has been activated!'
    @body[:url]  = "Visit #{HOST}!"
  end
  
  def forgot_password(user)
    setup_email(user)
    @subject    += 'You have requested to change your password'
    @body[:url]  = "#{HOST}/reset_password/#{user.password_reset_code}" 
  end

  def reset_password(user)
    setup_email(user)
    @subject    += 'Your password has been reset.'
  end   
  
  protected
    def setup_email(user)
      @recipients  = "#{user.email}"
      @from        = %("/Poke by carmelyne" <CT@yourrailsapp.com>) # Sets the User FROM Name and Email
      @subject     = "[YourRailsApp] "
      @sent_on     = Time.now
      @body[:user] = user
    end
end

Step 3: All about app/views/user_notifier/activation.rhtml

This gets sent out for the activation email so you can change the verbiage to something like this:

1
2
3
4
5
Thank you!

<%= @user.login %>, your account has been activated.  You may now start using the member only features.

<%= @url %>

I think that should be it. :)

I wrote this up to give you an idea for activation. If you extended it way beyond for forgot_password/reset_password, make sure you extend your user model and controller to handle these additional functions. More snippets....

Extras

1
2
3
# more for routes
map.forgot_password '/forgot_password', :controller => 'users', :action => 'forgot_password'
map.reset_password '/reset_password', :controller => 'users', :action => 'reset_password'
1
2
3
4
5
6
7
8
9
10
11
12
# app/models/user_observer.rb
class UserObserver < ActiveRecord::Observer
  def after_create(user)
    UserNotifier.deliver_signup_notification(user)
  end

  def after_save(user) 
    UserNotifier.deliver_activation(user) if user.recently_activated?
    UserNotifier.deliver_forgot_password(user) if user.recently_forgot_password?
    UserNotifier.deliver_reset_password(user) if user.recently_reset_password?   
  end
end

Update

But of course, there's a much better resource for the plugins, I was just referred to it after this long post from the man himself => Rick's Stikipad for Acts As Authenticated and RESTful authentication.

The additional methods for activation/forgot_password/reset_password does not fall under REST.

Aliases, Growl & Rspec

August 17, 2007 @ 02:01 PM | posted by carmelyne

(last updated: 08.17.07)

New tools new tool new tools

1. Aliases in bash

I'm a mac newbie. It sounds like a bad thing but it's not. Many moons ago, I only watched people type ss on their terminals and tada! it magically starts the built in webrick/mongrel server. I've been meaning to get aliases working since I converted but never got around to actually doing it. Thankfully, John Nunemaker posted his I Can Has Command Line? article. I can do bash magic now. My bash talk: ss sc a e et sup wu omg inbd idk my bff jill tinf! I think I'll use those for shortcuts anyway. ;p

2. Growl

I am a happy peepcoder. I recently saw the RSPEC Basics PeepCode. Geoffrey had a happy face/ sad face flashing bar on his screen when he would run tests. Oh, I so want. I want! You'll just have to buy the peepcode now, dont you? Anyway, it was Growl. I installed Growl but can't get it to work with autotest. Now I just do "a" to run autotest but I get this error: "177 examples, 0 failures sh: line 1: growlnotify: command not found". Obviously, I missed something here. I copied the .autotest file to ~
I'm off to search for a fix and will post it here too as an update.....

Update:

I knew I was missing something. I had to install growlnotify that came with the install files. (http://growl.info/documentation/growlnotify.php). I got my happy/sad bars now!

3.RSpec

New to RSpec and would you hold it against me if I said lazy with writing test? Ok then no, I love writing tests!!! Learning RSpec makes it easier to do test. I find that I do like BDD. I'm no expert but it's very fun to do, that I can say.

Snippets: Rails to_param

August 09, 2007 @ 05:08 PM | posted by carmelyne

(last updated: 08.09.07)

ID + permalink. The id gets a to_i

1
2
3
4
5
6
7
8
9
# using .join
def to_param
  [id, permalink].join('-')
end

# just another way to do it
def to_param
  "#{id}-#{permalink}"
end

REST, LiteSpeed & Attachment_fu

August 03, 2007 @ 12:42 PM | posted by carmelyne

(last updated: 08.09.07)

The big picture is with the redirects.


The quick work around...

If you've read my post about FreeImage, then you might be interested to know about the conflict I encountered with a RESTful app on LiteSpeed and using attachment_fu.

This was quite perplexing to be honest. I installed attachment_fu on a restful app, tested on my dev environment which is using Mongrel. I committed to my svn, updated files served on LiteSpeed and uh oh, the upload feature wont work. There's no error message, nothing gets saved at all and returns back as a 200 code. I couldn't debug alas I'm not the all perfect coder either. /wink /wink. I resorted to finding a work around.

First let's get some things clear, the conflict with REST, LiteSpeed and Attachment_fu is on another slice but not on this blog's slice. When I was looking for a work-around the first thing I did was to test the attachment_fu on this blog done by Rick Olson. Justin Palmer did the UI which is great. First, it wouldn't work since I had to give proper permissions to the assigned public image folder. Then everything after that was fine and dandy. Why does it work on here and not on the other slice. I go deep into the code reading line by line but time is running short. I need the upload feature working like yesterday.

For a quick fix, I thought to myself that I will just get LiteSpeed to work with Mongrel for the time being till I get a fix. I visited PickledOnion's excellent blog because he has the LiteSpeed set up goodies. I couldn't find any about Mongrel. That's fine since you really don't need Mongrel if you've chosen LiteSpeed. I emailed Paul aka PickledOnion and told him about my scenario. He said he was looking to getting attachment_fu to work on his project so he'll let me know if he ran into any issues. Us slicers have that special slicer bond. I don't know what that means but OK. ;p

I'm very happy with using LiteSpeed. The free version is good for a simple less traversed site like this blog of mine. Now having said all that, back to the workaround. I went now to the LiteSpeed and Mongrel sites to find some docs on how to set it up. Unfortunately, no docs on LiteSpeed with Mongrel at the LiteSpeed site but there was a short version on the Mongrel site. The one on the Mongrel site is a bit too complex, I can write down my fewer steps for a next blog post. After that, the work around was great. The upload function works under LiteSpeed, Mongrel using attachment_fu.

It continues....

It doesnt stop there. A few nights ago, just one of those long coding nights, I get an email back from Paul saying he has encountered the same issues I was having with LiteSpeed. He's heavy into the detailed configurations and was able to figure out some fixes. He's posted a ticket on the LiteSpeed forums to look into the issue. It looks like the LSapi version has issues with the restful redirects. The LiteSpeed support team is now looking into this so we'll see but for now, I'll be trying Paul's fix. The ticket is right here. It has the fix Paul suggested. I hope they patch it.

Update: (Aug. 5, 2007)

The LiteSpeed Team has updated the LSapi version to perform redirection more intelligently and to do redirect if there is an index file under that directory, otherwise, return it as a 404; that way the URI will be kept when handled by rails dispatcher. The thread

I've tested the LiteSpeed Enterprise version and all works perfectly. Restful Rails app with Attachement_fu on LiteSpeed is a happy little working wonder now.

Unrelated Windows Issue: (Aug. 7, 2007)

If you found this post while looking for a windows solution to error: 'Size is not in the list', I recommend adding the :size option on the model. Starting from 0.kilobytes to your max upload limit as sampled below.

1
2
has_attachment :content_type => :image,
               :size => 0.kilobytes..500.kilobytes

FreeImage on my Slice

July 27, 2007 @ 01:21 AM | posted by carmelyne

(last updated: 08.03.07)

FreeImage woes are better than RMagick woes.



First I tried installing FreeImage using this article:
http://seattlerb.rubyforge.org/ImageScience.html

Unfortunately, I get an error with make:

1
2
3
4
Source/Metadata/Exif.cpp:498: error: cast from 'BYTE*' to 'DWORD' loses precision
make[1]: *** [Source/Metadata/Exif.o] Error 1
make[1]: Leaving directory `/usr/local/src/FreeImage'
make: *** [default] Error 2

And If I proceeded with sudo make install, another error:

1
2
3
4
5
6
7
8
make -f Makefile.gnu install 
make[1]: Entering directory `/usr/local/src/FreeImage'
install -m 644 -o root -g root Source/FreeImage.h /usr/include
install -m 644 -o root -g root libfreeimage.a /usr/lib
install: cannot stat `libfreeimage.a': No such file or directory
make[1]: *** [install] Error 1
make[1]: Leaving directory `/usr/local/src/FreeImage'
make: *** [install] Error 2

After Googling awhile I found another repo for FreeImage.

So Let's try this again:

1
2
3
4
5
6
cd /usr/local/src
sudo wget http://ftp.cica.es/ubuntu/ubuntu/pool/universe/f/freeimage/freeimage_3.9.3.orig.tar.gz
sudo tar -xvf freeimage_3.9.3.orig.tar.gz
cd freeimage-3.9.3.repacked/FreeImage
make
sudo make install

Then I did:

1
2
gem install -y rubyinline
gem install -y image_science

Now off to my attachment_fu and crossing my fingers that it works.... Yup it works.

I'm not sure if freeimage_3.9.3.orig.tar.gz is the latest version but I'm happy enough that it works with attachment_fu.

I really have no idea why I got the errors above but one thing is for sure: It didn't work for me!

Compiling Ruby 1.8.6 on Ubuntu

July 17, 2007 @ 09:26 AM | posted by carmelyne

(last updated: 08.09.07)

Lets do this quickly:

Note: This is not for an upgrade.

  1. cd /usr/src
  2. sudo wget http://rubyforge.org/frs/download.php/18421/ruby-1.8.6.tar.gz
  3. sudo tar -xvf ruby-1.8.6.tar.gz
  4. cd ruby-1.8.6
  5. sudo apt-get install build-essential
  6. ./configure
  7. make test
  8. make
  9. sudo make install
  10. ruby -v (# == ruby 1.8.6 (2007-03-13 patchlevel 0) [x86_64-linux])
  11. irb (# make sure irb works)

Then just do a quick update sweep for ubuntu:

  1. apt-get update
  2. apt-get dist-upgrade

UPDATE: Getting script/console to work

Error:
/usr/local/lib/ruby/1.8/irb/completion.rb:10:in `require’: no such file to load – readline (LoadError)

Eeek now script/console won't work. So let's fix that. We'll go back to the archive and do the following:

  1. cd /usr/src/ruby-1.8.6/ext/readline
  2. ruby extconf.rb
  3. make
  4. sudo make install

Do I need a disclaimer? Hey! I was on my own too when I did this compile. ;p

Snippets: Rails 'A'..'Z' Paginate

June 24, 2007 @ 09:40 PM | posted by carmelyne

(last updated: 06.25.07)

'A'..'Z' paging cause I'm being lazy & I don't want to mess around with default paginate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Starts with 'A'..'Z' Paginate / model
def self.sort(sort)
  if sort
    find(:all, :conditions => ['name LIKE ?', "#{sort}%"])
  else
    find(:all, :order => 'name')
  end  
end
  
# index action / controller
@models = Model.sort(params[:sort]) 
 
# Sort link A-Z / view
<a href="models?sort=A">A</a>

Snippets: Ruby Switch Statements

June 20, 2007 @ 10:47 AM | posted by carmelyne

(last updated: 06.24.07)

1
2
3
4
5
case foo
   when 1    then puts "Foo is equal to 1"
   when 2..9 then puts "Foo is between 2 and 9"
   when 10   then puts "Foo is equal to 10"
end

Source: http://railsforum.com/viewtopic.php?pid=27834#p27834

Roundtable: Women in Development

June 19, 2007 @ 08:26 PM | posted by carmelyne

(last updated: 06.19.07)

My apologies. It just didn't cross my mind to post about the Women in Development podcast when it first came out. I had a lot in my plate right after the conference. I was mostly trying to catch up with tasks at work since I'm acting as Lead Developer at PWIM for the time being.

Anyhow, in these podcasts you will hear the views of women on the absence decline of women in development and absence during conferences. Desi shares her vision and goals about where she wants devChix to be. devChix is a collective group of women with backgrounds in Computer Science and Computing. It was so immensely uplifting to be in the company of such great women that day. I enjoyed participating in the discussion. I was more nervous than anything else during the entire podcast session. Mind you, I was sitting two feet away from Geoffrey Grosenbach. Cool, right?

After hearing the podcast again, I think it's time to live up to my nickname "multi-talented". Oh the pressure mounts!

Collection of comment styles.

June 03, 2007 @ 07:36 AM | posted by carmelyne

(last updated: 08.08.07)

Single line comments:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
AppleScript (*Hello I am a comment*) 
ASP <% 'Hello I am a comment. %>
Bash # Hello I am a comment 
C // Hello I am a comment
C++ /* Hello I am a comment */
CSS /*  Hello I am a comment */
Coldfusion <!--- Hello I am a comment --->
DOS :: Hello I am a comment 
Erlang % Hello I am a comment 
HTML <!-- Hello I am a comment -->
Java // Hello I am a comment 
JavaScript  /* Hello I am a comment */ 
Liquid {% comment %} Hello I am a comment {% endcomment %} 
Lua -- Hello I am a comment --
Perl # Hello I am a comment  
PHP <?php // Hello I am a comment ?>
Python # Hello I am a comment  
Regex (?#Hello I am a comment)
Rails <%# Hello I am a comment %>
Ruby # Hello I am a comment 
Smarty {* Hello I am a comment *}
XML <!-- Hello I am a comment -->
YAML # Hello I am a comment  

I've been wondering what comment style is used in Liquid.

Got any to share?

Recap of my RailsConf 2007 Experience

May 22, 2007 @ 12:53 PM | posted by carmelyne

(last updated: 06.19.07)

Image Credit: Dave Thomas' Website



What did I like most about the conference?

That would have to be the keynotes.

DHH didn't announce anything life changing but I think it's a challenge to continue exploring the beauty of REST and the simplicity with a great productivity feel of the whole Rails on Ruby architecture. On the other end of the spectrum, we have Avi Bryant who I'd teasingly call now the Adam Brody of computing. It was great to hear Avi's perspective.

Tim Bray's reality check that Java, PHP, .NET will not go away and will be there to stay. That's fine. As a developer, I do prefer that because if we're all doing Rails then it would be plain silly. Imagine the 5 sec maintenance and off to the beach skit by RailsEnvy? I'd get no beach spot! Tim also mentioned that there were no women in the conference or perhaps the lack of. As a male geek in the development world, would you encourage your daughters to enter it? I would like to hear your thoughts on that.

Koz and Buck. That was really cool to see them refactor and why they recommend the different things they recommend. I am a big fan of The Rails Way blog.

I love Cyndi Mitchell's final slide on the enterprise during the keynote "Bring Ruby to the Enterprise. Not the Other Way 'Round." She's an excellent speaker and I met her briefly at Rock Bottom during one of the party nights.

Dave Thomas is The Uber! I wanted to yell I love you Dave! when he briefly mentions rubychix.com and turned around and showed their very own white male version site. I wish someone would send me my pic from the rubychix site cause I never got the chance to see the pic.

Ze! That keynote made me cry and laugh at the same time. I actually checked the safety cards and was looking for the bags on the plane on my way home to Chicago.

Lastly, RailsEnvy's series of "Hi, I'm Ruby on Rails".

What were my favorite sessions?

Spam I Have Known by Jim Weirich and Memcaching Rails by Chris Wanstrath.

What were my favorite BOF sessions?

Hackety Hack with Snackety Snack. Err was that the right title? It was engaging. All the thoughts and suggestions were so brilliant that I wish _why heard them all.

Cool people I met?

I can't even begin to enumerate them all. There were a TON of wonderful people. Let's do the reverse instead. Who were the people I wish I got the chance to approach, say hi to and chat with for a bit? Those would be Damon Clinkscales, Eric Hodel for sharing his Coda notes with me, Marcel, Tobias, Koz and Jamis of the core team, PragDave, Mike Clark and Ze!

Coolest thing during the conference

As of today, $33,000 was raised for charity by attendees. Now how cool is that?

Getting female tees from Peepcode from Geoffrey Grosenbach!!!

Sitting down with other female developers in room 201 on Sunday to participate in the DevChix podcast interview by Geoffrey. That was really cool. I'm looking forward to its release.

Updated: 05/22/2007

Forgot Chad Fowler's and Joey Devilla's ode to DHH via "I'm A Noob".



Snippets of 06/24/07

Rails 'A'..'Z' Paginate

1
2
3
4
5
6
7
8
9
10
11
# Starts with 'A'..'Z' Paginate / model
def self.sort(sort)
  if sort
    find(:all, :conditions => ['name LIKE ?', "#{sort}%"])
  else
    find(:all, :order => 'name')
  end  
end

# index action / controller
@models = Model.sort(params[:sort]) 
RailsConf 2006
I heart devChix