Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Rubify

Takes a string, such as a post title ("Rat Brains Fly Planes") and convets it into a ruby style variable name that can be used as an id or permalink url ("rat_brains_fly_planes")

Posted by Duane Johnson on rails list:
Here's the modified String class. This one
squeezes non-alphanumeric character sequences down to one underscore
and also makes sure it doesn't start or end with an underscore:

   1  
   2  class String
   3    def rubify
   4      downcase.gsub(/\W/, ' ').squeeze.strip.gsub(' ', '_')
   5    end
   6  
   7    def rubify!
   8      replace rubify
   9    end
  10  end

"!Hell93 o3#$@ the___re , dude".rubify
=> "hel93_o3_the_re_dude"

Luke Redpath suggested the following naming convention:
ID is short for identification the related verb of which is identify.

The appropriate verify_ macro would be verify_identity_of

A more conventional Ruby idiom would be to_id() (like to_s, to_i etc.).

   1  
   2  "My, what a beautiful day!".to_id
   3  
   4  => "my_what_a_beautiful_day"


If thats not clear enough or possibly confusing with the normal use of id in a Rails app, perhaps to_identifier() instead.

how to handle multiple flash keys

posted by Scott Raymond on rails list

I generally like to add something like this to my application_helper.rb:

   1  
   2  def flash_div *keys
   3    keys.collect { |key| content_tag(:div, flash[key],
   4                                     :class => "flash #{key}") if flash[key] }.join
   5  end


...and then this in my layouts/application.rhtml:

   1  
   2  <%= flash_div :warning, :notice %>


Now, if my controller puts anything into flash[:warning] or flash[:notice],
they'll render like:

   1  
   2  <div class="flash warning">Warning here</div>
   3  <div class="flash notice">Notice here</div>


Nice and DRY, and easy to style. If I ever need some other flash key besides :warning or :notice, I can just add an argument to the flash_div call and I'm set.

standardizing rails flash messages

a proposal from Luke Randall on the rails mailing list

   1  
   2  :notice for positive feedback (action successful, etc)
   3  :message for neutral feedback (reminders, etc)
   4  :warning for negative feedback (action unsuccessful, error encountered, etc)


Then, in your controller or view you could place code such as the following:

   1  
   2  FLASH_NAMES = [:notice, :warning, :message]
   3  
   4  <% for name in FLASH_NAMES %>
   5    <% if flash[name] %>
   6      <%= "<div id=\"#{name}\">#{flash[name]}</div>" %>
   7    <% end %>
   8  <% end %>
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS