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
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>
Ok, so here's something useful for using keyboard short cuts to navigate through a small supporting application:
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('+hm',function() { document.location.href='' });\n"
end
javascript_tag(code_string)
end
Then in a layout file just:
Makes use of a nice shortcuts.js lib.
This is a fragment of a conversation on our internal IRC with my solution for refactoring a piece of code:
Granted, it is not as clear as the original, but it is hard to resist it from the aesthetic point of view.
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.
define_readonly_class(readonly_db) unless ActiveRecord.const_defined?(readonly_class_name(readonly_db))
end
"Generated"
end
ActiveRecord.module_eval %Q!
class < Base
self.abstract_class = true
establish_connection configurations[RAILS_ENV]['']
end
!
end
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'].
@@cached_configs ||= {}
@@cached_config_mtimes ||= {}
base_name = "config/.yml"
filename = File.join(RAILS_ROOT, base_name)
raise "ERROR: Config not found: " 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
