Sunday, June 17, 2007

Code Digest #1

When you program for a living, you write lots of code. There is often some code that you are fond of. We start the Code Digest series to present such code written by the RHG developers. We encourage other teams and individual developers to share similar snippets in their blogs so we all can learn from each other and become better rails developers.

Daniel Silva



<%= link_to(image_tag("/images/icon.gif", :style=>"padding-right:0px;"), {:controller => '/registration', :action => 'login', :dest => request.request_uri}, {:style => ""}) %> 

With this line, I can create an image link using Rails code, to take advantage of the power of routes in Rails while still creating this kind of structure: <a href="#"><img border="0"/></a>



Jack Dempsey



Ok, so here's something useful for using keyboard short cuts to navigate through a small supporting application:
def include_keyboard_shortcuts

hotkey = 'Ctrl+Shift'
code_string = ''
keys = {
'm'=>'/account_info/show',
's'=>'/account_info/index',
'c'=>'/menu/go?menu_action=new_customer',
'p'=>'/products',
'o'=>'/account_info/orders',
't'=>'/order_tracker',
'x'=>'/auth_sessions/destroy',
'r'=>'/current_users/reset_password'
}

current_user_needed = %w{m o r}

keys.each_pair do |k,v|
next if current_user_needed.include?(k) && current_user.nil?
code_string << "shortcut('#{hotkey}+hm#{k}',function() { document.location.href='#{v}' });\n"
end

javascript_tag(code_string)

end



Then in a layout file just:
<%= javascript_include_tag 'shortcuts' %>
<%= include_keyboard_shortcuts %>



Makes use of a nice shortcuts.js lib.


Val Aleksenko


This is a fragment of a conversation on our internal IRC with my solution for refactoring a piece of code:
May 07 14:07:56 <Anthro> There has to be a better way to do this (x and y are non-negative integers): increment = (x!=0) ? ( (y!=0) ? 0 : 1 ) : -1
May 07 14:08:22 <Anthro> I think it can be done with math instead of logic.
May 07 14:16:56 <jack> Anthro: have you thought about using sin and cos? ;-)
May 07 14:18:42 <muzzy> (x <=> 0) <=> (y <=> 0)



Granted, it is not as clear as the original, but it is hard to resist it from the aesthetic point of view.

Val Aleksenko


I love writing dynamically generated methods and classes in Ruby as the next guy. When I was writing acts_as_readonlyable, I needed to manage multiple connections. I found that the easiest solution for managing active connections was generation of an AR class for each read-only definition and borrowing the connection from it. The usage is acts_as_readonlyable :read_only_entry_in_database_config.
def acts_as_readonlyable(readonly_db)
define_readonly_class(readonly_db) unless ActiveRecord.const_defined?(readonly_class_name(readonly_db))
end

def readonly_class_name(db)
"Generated#{ db.camelize }"
end

def define_readonly_class(db)
ActiveRecord.module_eval %Q!
class #{ readonly_class_name(db) } < Base
self.abstract_class = true
establish_connection configurations[RAILS_ENV]['#{ db }']
end
!

end



Warren Konkel


The ConfigFile class is a quick and easy way to load YAML files located in your Rails application's config directory. Simply place a YAML file into your config directory and then access it like a hash. For example this will read your config/database.yml: ConfigFile['database']['production']['adapter'].
class ConfigFile
def self.[](arg)
@@cached_configs ||= {}
@@cached_config_mtimes ||= {}

base_name = "config/#{arg}.yml"
filename = File.join(RAILS_ROOT, base_name)
raise "ERROR: Config not found: #{base_name}" unless File.exists?(base_name)

if @@cached_configs[arg].nil? || @@cached_config_mtimes[arg] < File.stat(filename).mtime.to_i
@@cached_configs[arg] = YAML.load(File.open(filename))
@@cached_config_mtimes[arg] = File.stat(filename).mtime.to_i
end

@@cached_configs[arg]
end
end

5 comments:

Unknown said...

the first example would be improved by the use of a named route and {style => ""} is unnecessary

the second example, the hotkeys, made this article worth it for me - i've never bothered to add them :)

the third example is interesting, i wonder what the context was

4th and 5th are interesting - i like the 5th.

Good article, thanks.

Dr Nic said...

The hotkeys snippet is awesome. I assume pressing each causes a redirect (document.location = )? Could you specify a function() instead?

Dr Nic said...

If only I'd spent 30 more seconds reading the snippet I would have seen the document.location.href code. Ok, so I just write whatever I want in the shortcut function call.

Unknown said...

In response to the sin and cos example, its always better to be obvious than clever in my opinion.

Anonymous said...

The comparison-refactoring is very nice :)
Nevertheless it fails for x=0 and y=0, with (x-0.5 <=> 0) <=> (y <=> 0) fixing that.