Structuring CFCs a Little Like Ruby
May 18, 2010 · Chris Peters
As I hit the books and learned about Ruby on Rails a couple years ago, there was one thing that I admired about how Ruby handles public and private sections of classes.
As I hit the books and learned about Ruby on Rails a couple years ago, there was one thing that I admired about how Ruby handles public and private sections of classes.
Take this, for example:
class PostsController < ApplicationController | |
before_filter :find_post, :only => [:show, :edit, :update, :destroy] | |
def show | |
# ... | |
end | |
def edit | |
# ... | |
end | |
def update | |
# ... | |
end | |
def destroy | |
# ... | |
end | |
private | |
def find_post | |
@post = Post.find(params[:id]) | |
end | |
end |
Using the private
keyword, the interpreter knows that all methods defined in the section afterward are private. It’s a pretty clean way of demarcating different blocks of code that have different roles.
While we have no such set of keywords for CFML except at the function level, why not use comments to do similar structuring of your CFCs?
<cfcomponent extends="Controller"> | |
<!-------------------------------------> | |
<!--- Public ---> | |
<cffunction name="init"> | |
<cfset filters(through="findPost", only="show,edit,update,destroy")> | |
</cffunction> | |
<cffunction name="show"> | |
<!--- ... ---> | |
</cffunction> | |
<cffunction name="edit"> | |
<!--- ... ---> | |
</cffunction> | |
<cffunction name="update"> | |
<!--- ... ---> | |
</cffunction> | |
<cffunction name="destroy"> | |
<!--- ... ---> | |
</cffunction> | |
<!-------------------------------------> | |
<!--- Private ---> | |
<cffunction name="findPost" access="private"> | |
<cfset post = model("post").findByKey(params.key)> | |
</cffunction> | |
</cfcomponent> |
A perfect translation? No. But an idea on how to use some simple comments to make your life easier when maintaining your code in the future.
I’ve taken it a step farther and also have been creating “Filters” sections for filters, just before “Private” methods.