Software Development |
Ruby on Rails
altered_beast Ruby Style
The authors of altered_beast use a rather terse style of Ruby. I imagine, for altered_beast at least, this is because the goal was 500 lines of code or less. In my opinion the gain in brevity was achieved via a loss in clarity. I'm sure there are counter arguments.
Anyway here are some examples.
condition? || action
The admin_required function is an example.
lib/authenticated_system.rb (snippet)
def admin_required admin? || access_denied end
To me this suggests that access_denied is checking some kind of access status. This isn't the case. The function actually contains the processing to deny access including redirecting the browser etc. Bundling the check and the action as an OR statement ensures a boolean value is returned.
if ... elsif ... else ... end ... or
The find_user method in the Users controller has a variation on the admin_required example with an additional twist.
app/controllers/users_controller.rb (snippet)
def find_user
@user = if !admin?
current_site.all_users.find params[:id]
elsif params[:id] == current_user.id
current_user
else
current_site.users.find params[:id]
end or raise ActiveRecord::RecordNotFound
end
RadRails flags this up with a warning and tells me that Ruby interprets that code as:
def find_user
( @user = if !admin?
current_site.all_users.find params[:id]
elsif params[:id] == current_user.id
current_user
else
current_site.users.find params[:id]
end ) or
( raise ActiveRecord::RecordNotFound )
end
Like admin_required it puts the error handling after an ||, or in this case an 'or'.
The other bit of style that jumps out is the assignment to an if-elsif-else statement.
!!
In English a double negative is considered a bad thing because it confuses the listener/reader with what was meant. However altered_beast uses the Ruby equivalent of a double negative (!!) quite a lot. For example:
app/models/user.rb (snippet)
def moderator_of?(forum) !!(admin? || Moderatorship.exists?(:user_id => id, :forum_id => forum.id)) end
There is a reason for this. In ruby false and nil are treated as false in a Boolean context and all other values are treated as true. Ruby also has an explicit true value. As the && and || operators ultimately return the value of one of the operands they do not necessarily return an explicit true or false. In contrast the ! operator always returns an explicit true or false. I am guessing, and I could be wrong, that altered_beast uses this fact, and the double not (!!), to ensure the result of a Boolean test is an explicit true or false.
