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