attachment_fu (with rmagick) on windows not working

man, i had a heck of a time getting attachment_fu (using rmagick) on windows working tonight. let me just start with this: if you're having problems, just reboot. it would have saved me an hour.

i followed all the instructions and fixed all the hacks, yet for some reason thumbnails were not generating and the height and width was not being saved. there are lots and lots of articles out there on these topics. most of them discuss how the size isn't being saved, but in my case the size was being saved.

how'd fix it: i rebooted the machine and it worked.

How To Upgrade to Rails 2.0 from 1.2.5

I had to upgrade my Rails app last night to 2.0.2 from 1.2.5. This is a brief overview of what it took to make it happen. I'll write some other posts soon with more details. A little background: I'm using InstantRails and the Aptana RadRails IDE on Windows XP SP2.

Here's what I did:


  • Installed Instant Rails 2.0.

  • Checked out a working copy of my code from SVN

  • Updated environments.rb: RAILS_GEM_VERSION = '2.0.2'

  • Fired it up: didn't work.

  • I'm using acts_as_tree and acts_as_list, so I needed to install those plugins.

  • Fired it up: didn't work.

  • I'm also using Comatose, and there was an error with the "template_root". Bottom line: after reading some message boards, etc. I removed and reinstalled the Comatose plugin and that fixed it.

  • Fired it up: didn't work.

  • Was getting this error:

    Status: 500 Internal Server Error
    A secret is required to generate an integrity hash for cookie session data. Us
    e config.action_controller.session = { :session_key => "_myapp_session", :secret
    => "some secret phrase of at least 30 characters" } in config/environment.rb


    Well, that message says it all, so I changed that.

  • Fired it up: was working. Now, navigated my app...errors.

  • Had to change ':dependent => true' to ':dependent => :destroy'

  • Removed the line(s) config/environments/development.rb:12: config.breakpoint_server = true
    from configuration since the setting has no effect anymore.
    Instead, start `script/server` with the "-u" or "--debugger" option (or "-h"
    to see all the options). This wasn't causing an error, but while trying to figure out the dependent => :destroy thing, I read it on someone's blog, so I removed it.

  • Also, had to install the classic_pagination plugin. (Really, every blog out there says I should upgrade to will_paginate, but my blog is about progress vs. perfection. Old school pagination works for me for now, so I'll stick with it.)

  • Fired it up...everything running, but still some functionality isn't working. (Gee...I wish I'd writen *all* the unit tests. Okay, let's debug.)

  • Opened RadRails, imported existing directory into a project.

  • Got this error: rad rails "Cannot find gem for Rails ~>2.0.2.0:"...had to switch workspace because I installed the new Instant Rails and RadRails was still pointing at the old one. (Not an issue if you overwrite, but I'm running my concurrently.)

  • Hmmm...the server runs through Aptana RadRails, but debugger is slow as heck...turns out that I updated ruby-debug-ide when I updated gems and that un-checked the checkbox for using the fast debugger in the IDE. Also, had to install ruby-debug-base. (I don't think this was required before, but once I installed it the debugger worked.)


Whew, well, I haven't found my bug yet, but that's how far I've progressed. Hopefully this will help the next guy out.

Rails vs. ASP.NET (Really, Ruby vs C#)

Where have I been...why the lack of posts: a) holidays, b) knee injury playing basketball (that required surgery to repair) has slowed me down, c) recently, I've started to work on a project where ASP.NET using C# was the requirement.

So, I haven't been working in Rails for a few weeks and it's been a few years since I've used ASP.NET or C#, so I've had to jump back into it a little to refresh myself.

Now, look, I'm not trying to start a religious war here: ASP.NET and Rails each have their own benefits and drawbacks. However, I would like to say this: for simple web sites Rails is so much easier.

Here's a simple example: I've got a URL stored in the database, such as http://www.mysite.com/foo/fee/foh.htm and I need to get the foh.htm (which isn't stored).

ASP.NET with C#

    public string FileName
{
get
{
char[] delim = { '/' };
string[] a = this.Url.Split(delim);
return a[a.Length - 1];
}
}

Rails with Ruby
  def filename
self.url.split('/').last
end

I'm sure I'm not the first person to make this comparison. I just felt compelled to speak out about the many moments during the day where it takes me several minutes longer to do something with ASP.NET and C# than Ruby and Rails.

How to Make Subversion via HTTP work with RailsMachine (and Capistrano)

Last night I setup my site on RailsMachine. Overall, it was a very pleasant experience. One bugaboo that I ran into:

I have my Subversion repository setup using http, not svn+ssh. The repository is hosted at Joyent and I don't recall why I set it up this way, but there must have been a reason.

Anyhoo...so, I'm plugging away with RailsMachine and using Capistrano for the first time and it's all pretty sweet, except for I can't seem to access my svn repository. Cap would reach the point in the script where it made the HTTP request and I would see the HTTP authentication, but I had no way to type in my user/pass combo, and it would fail.

Long story short: RailsMachine requires that you run Cap using a user called "deploy", and those are the credentials that Cap passes via HTTP Authentication to the svn repository. So, I was able to get it to work by simply creating a user for my svn repository called "deploy" with the same password as "deploy" on my RailsMachine server. Everything works fine now!

more on attachment_fu on windows

In my previous post about attachment_fu (with rmagick) on windows, I did something sort of silly in the #create action of my controller: Windows required a little time to catch up because the file system loaded the file slower that attachemnt_fu needed it. To solve that problem, I added "sleep 5" immediately before MyObject#save.

The problem with that hack is every time I need to #save I have to remember to insert the "sleep 5" hack. That's a mistake waiting to happen. So, I moved the sleep to the model, like so:


class MyObject < ActiveRecord::Base
def before_save
sleep 5 ## <<-- pauses so Windows can catch up.
end
end

It's much more logical that this code is part of the model because the delay is fundamentally a part saving the object, not a part of responding to an action.

This also address the notion of keeping your controllers skinny and your models fat. Jamis Buck blogs very eloquently about this notion here.

attachment_fu (with rmagick) on windows

Today, I've been working to get attachment_fu working with rmagick on Windows. At first, it wasn't uploading the file properly and after much Googling implemented these changes to get it working.

1. I added a pause to my #create in order to allow Windows time to catch up. In short, Ruby is moving faster than the Windows file system, and it was trying to create a record for a file that didn't exist yet. Here's what I did:

  def create
@upload = Upload.new(params[:upload])
sleep 5 ## <<-- pauses so Windows can catch up. Probably would be
## smart to make this something like sleep 5 if OS == Windows
## obviously, that's not the right syntax.
if @upload.save
flash[:notice] = 'Upload was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end

I am fully aware that this is a hack, but it gets the job done.

2. I continued to get the error message "Size is not included in the list". Long story short, this is the error message attachment_fu returns when the file size exceeds the limit set in the model. In addition, it provides this message if no file is provided at all which is a duplicate error because validates_as_attachment is already doing a validates_presence_of against the size.

So, in order to create some better error messaging, and following the notions of how to hack a plugin from this blog post, I created a new plugin called attachment_fu_hacks and in init.rb added this code:
klass = Numeric
klass.class_eval do
def to_human
units = %w{B KB MB GB TB}
e = (Math.log(self)/Math.log(1024)).floor
s = "%.1f" % (to_f / 1024**e)
s.sub(/\.?0*$/, ' ' + units[e])
end
end

klass = Technoweenie::AttachmentFu::InstanceMethods
klass.module_eval do

# overrides attachment_fu.rb:342 b/c to provide better error messages
def attachment_attributes_valid?

attr_name = :size
enum = attachment_options[attr_name]
val = send(attr_name)
if !enum.nil? && !val.nil? && !enum.include?(val)
err_msg = enum.end.to_human
errors.add attr_name, "of file is too big (must be less than #{err_msg})"
end

attr_name = :content_type
enum = attachment_options[attr_name]
val = send(attr_name)
if !enum.nil? && !val.nil? && !enum.include?(val)
err_msg = enum.join(', ').gsub(/image\//, '.') unless enum.nil?
errors.add attr_name, "is not supported (must be #{err_msg})"
end
end
end

klass = Technoweenie::AttachmentFu::ClassMethods
klass.module_eval do
# overrides attachment_fu.rb:106 b/c i don't think it's necessary
# to evaluate size or content_type if there is no file
def validates_as_attachment
validates_presence_of :filename
validate :attachment_attributes_valid?
end
end

I recognize that there might be a more idiomatic Ruby way to write attachment_attributes_valid?, but I prefer this because it's very clear as to what's going on.

Issue with has_many and Array.empty?

I've posted a narrative of my issue on the Google Rails Group:


/app/controllers/document_groups_controller.rb
def show
@document_group = DocumentGroup.find(params[:id])
@journal = Journal.find(params[:journal_id])
@document_group_templates = @document_group.document_templates
@logger = RAILS_DEFAULT_LOGGER

#
# this is the money line: comment it out and @document_group_templates.empty?
# is true in the view. leave it in, and it's false. true is correct.
#
@logger.debug "###### --->" + @document_group_templates.inspect
#
# it turns out that this triggers the SQL to be run by Rails that acutally
# populates the @document_group_templates Array.
#

render :action => :show, :layout => 'ajax_div'
end


/app/views/document_groups/show.rhtml
#
#@document_group_templates.empty? evaluates to true without the inspection above
#
<% if !@document_group_templates.empty? %>
#
# now, what's interesting is that if i change this to
#
# if @document_group_templates.count > 0
#
# that also triggers the SQL to be run. but, interestingly, #size does not
# trigger the SQL.
#
<ul>
<%
@document_group_templates.each do |child|
%><li><%= link_to child.name, :controller => :template, :action => :show, :id => child.id %><%
end
%>
</ul>
<% end %>

/app/models/document_group.rb
class DocumentGroup < ActiveRecord::Base
has_many :document_templates, :order => :document_group_position
acts_as_tree :counter_cache => true
end

/app/models/document_template.rb
class DocumentTemplate < ActiveRecord::Base
belongs_to :document_group, :counter_cache => true
acts_as_list :scope => :document_group, :column => :document_group_position
end

How to call render :partial properly

At some point, you may be going bananas because you're getting this error:

NoMethodError in DocumentController#new
undefined method `include?' for :new:Symbol

and the problem is that you're doing this somewhere:
render :partial => :new

instead of this:
render :partial => 'new'


This error is spawned by the method partial_pieces in /ruby/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_view/partials.rb:90 which is trying to figure out if the partial you're calling is in the directory of the current controller, or some other directory. Here's that code:
89      def partial_pieces(partial_path)
90 if partial_path.include?('/')
91 return File.dirname(partial_path), File.basename(partial_path)
92 else
93 return controller.class.controller_path, partial_path
94 end
95 end

The error comes from line 90. Seems like if this were inserted at line 89.5, then this problem could be handled more gracefully
partial_path = partial_path.to_s if partial_path.is_a? Symbol

given the fuzzyness of symbols and strings, it would seem to make sense to me.

How to Avoid and Infinite Loop with before_save and after_save

I have an entity that looks something like this:

journal
author_first_name
author_last_name
journal_name
journal_email_address

where
journal_name = author_first_name + ' ' + author_last_name
journal_email_address = journal_name + '-' id

I had journal_name and journal_email_address implemented as attributes on the Journal model, but the time came along where, for various reasons, it has become valuable to also store that information in the database. So, what I thought I’d do, in app/models/journal.rb:
def make_journal_name
self.journal_name = self.author_first_name + ' ' + self.author_last_name
end

def make_inbound_email
self.inbound_email = self.journal_name.gsub(/[^a-zA-Z0-9]/, '') + '-' + self.id.to_s
end
def before_save
make_journal_name
make_inbound_email
end

which works fine in the case of an update of an existing record. However, it does not work in the case of a creation of a new record because before saving self.id does not exist. The result was my e-mail addresses are looking like “SallyJones-” as opposed to “SallyJones-64”.

Okay, I thought, “since I need an ID to work with I’ll move this to after_save,” like so:
def after_save
make_journal_name
make_inbound_email
self.save
end

but that creates an infinite loop.

The solution to this problem is to use an undocumented method: update_without_callbacks.
def after_save
make_journal_name
make_inbound_email
self.update_without_callbacks
end

update_without_callbacks is an instance method on ActiveRecord::Base, but for some reason it’s undocumented. In fact, it explicitly has :nodoc set in the source, although I can’t figure out why. To me, it seems that having more documented is better than having less.

The Rails Way

A big part of using Rails is understanding that if you conform to "The Rails Way" things are much easier. Of course, The Rails Way might not work for your project, and in that case, Rails might not be the right framework choice. But, you have to learn The Rails Way in order to know.

I can't claim to explain The Rails Way completely, but I've been helping a new (to Rails) developer on my team get up and running, so I've been having to coach him to see The Rails Way.

I started by talking about "entities". An entity is a thing like a "widget"...some object in our application domain that we need to represent. By convention, the names of the database table, unit tests, models, controllers, views, layouts and helpers must always coordinated in Rails to the name of the entity. So, with our "widget" entity, this is how they should be:


  • DB Table: widgets
  • Model: app/models/widget.rb
  • Controller: app/controllers/widgets_controller.rb
  • View: app/views/widget/...
  • Layout: app/views/layouts/widgets.rhtml
  • Helper: app/helpers/widgets_helper.rb

The beautiful thing about Rails is that by using generators, this gets managed for you. Here’s the approach I always take when creating an entity. This can be done through an IDE (such as RadRails, which is what I use) or on the command line...I’ll use the command line here:

  • cd path/to/rails/app
  • ruby ./script/generate model Widget which will generate your model file and your migration file with the proper table name.
  • Open up the migration, add the appropriate columns and save.
  • rake db:migrate to apply your migration to the DB.
  • ruby ./script/generate scaffold Widget which will create your controller, views, layout and helper.

Generators create a starting point to start editing, and it also gets all the file names correct. Let’s talk about the editing that needs to happen. Personally, I always do my editing in this order:

  1. Migration
  2. Model
  3. Controllers
  4. Views
  5. Layouts

This makes the most sense to me because I’m starting with the raw data, and working my way forward to what the user sees on the web page.

A little background on controllers (a good article to read is this: http://www.softiesonrails.com/search?q=rest+101): Your standard CRUD controller has 8 actions:

  • Create (Create): /widgets/create
  • Show (Read): /widgets/show/:id
  • Update (Update): /widgets/update/:id
  • Destroy (Delete): /widgets/destroy/:id
  • New (precursor to create): /widgets/new
  • Edit (precursor to update): /widgets/edit/:id
  • List (lists all entities): /widgets/list
  • Index (the default action): /widgets

When, you generate your scaffold, it’s going to automatically generate the 8 actions above. When designing entities if you have methods that don't fit within one of those actions then it's typically an indication that your entity model could our should be designed differently.

(A great example of how it's all about entity design is the login and logout actions for a User. I was thinking the other day about where the login and logout methods belong because they make sense on a User, but they aren't one of the above eight actions. Of course, I was thinking about it all wrong: login and logout are really the Create and Destroy methods on the Session entity, and Session entities belong to a User.)

Finally, a note in regard to the relationships between views, controllers and models in the context of validation. The typical user pattern in relation to creating an entity is:

  • User visits /widgets/new page
  • Enters data, click submit.
  • /widgets/new POSTs to Widgets#create
  • Widgets#create puts the data in the DB, then (if you look at the scaffold generated controller)

    • If success, calls redirect_to
    • If fails, calls render :action => :new

Why in one case does it redirect, and the other does it render? It all has to do with a little method call that should appear in your new widgets view, i.e. /widgets/new:
<%= error_messages_for 'widget' %>

See, a model has the capability to validate it’s attributes (e.g. lookup validates_presence_of in the Rails docs for examples of these capabilities). When you call Object#save the validation routines are executed and if the model doesn’t validate (i.e. Object#save returns false) we render the new action again. error_messages_for looks up the failures and automagically renders error messaging.

The beauty of generators is that script/generate scaffold Widget sets all of this up for you.

The Problem with Rails Plugins

The other day Mark asked if I was using active_scaffold. The answer is that I have a perfect use for it, and I installed it, and it works perfectly for what I need it for. However, it also overrides some core Rails functions, and when I execute functionality in my portion of the app the active_scaffold version of those functions are throwing exceptions. For example:

class ActionController::Routing::RouteSet 
def generate_with_nil_id_awareness(*args)
args[0].delete(:id) if args[0][:id].nil?
generate_without_nil_id_awareness(*args)
end
alias_method_chain :generate, :nil_id_awareness
end

Now, to me, ActionController::Routing::RouteSet seems like a pretty core function in Rails. Of course, it may be the case that I’ve done something wrong and their updated version is catching that error. (You can read more on that here: http://groups.google.com/group/activescaffold/browse_thread/thread/1c4e2f30e8b00ac6/309665c0a85d65c8).

However, my thinking is that I don’t need some plugin f’ing with my app. In fact, this points to a major issue with plugins…they’re not these self-contained units, i.e. components...but, rather, they are mixed in with the core Rails framework and our apps. This means we must think very carefully about which plugins we’ll use because, effectively, we need to know them as well as we know our own code. In other words, they are not black boxes...they are just code we import into our app that somebody else wrote (and is kind enough to share). For example, active_scaffold installs 138 files, and who knows how many kLOCs of code, and who knows what funky stuff they’ve done.

So, long story short, I’m not using active_scaffold because I don’t trust that there isn't come code in there that's gonna mess up my app, and it's too much code for me to review and become familiar with. Any ideas on an alternative?

I’ve looked at Streamlined, Hobo Scaffolding Extensions. According to the docs, Streamlined doesn’t do nested records editing which I require, Scaffolding Extensions handles nested record editing, but isn't the best UX, and Hobo has the same problem as Radiant CMS...I have to put my app into theirs, not their app into mine. (However, both Radiant and Hobo seem like nice platforms for the right project, just not the one I'm currently working on.)

What does "idiomatic Ruby" mean?

From a chat with Mark today, in regard to reading a post where I used the word "idiomatic":

(10:10:42) Mark: idiomatic, what a word
(10:11:12) Scott Porad: yes, i don't even know what it means...but people
say it when they mean, "there's a more clever way to write this in ruby".
(10:11:26) Mark: Peculiar to or characteristic of a given language.
(10:12:05) Mark: nice, one of the descriptions of idiomatic, uses idiomatic
to describe it: Characterized by proficient use of idiomatic expressions

Acts As Authenticated and Reset Password

Using Acts as Authenticated, imagine this use case:


  • User forgets password...has reset code sent to their e-mail.
  • User receives e-mail, clicks link to reset password.
  • User arrives on reset password page and thinks, "hmmm...I think I'll go visit the homepage instead".
  • User types http://www.yoursite.com/ in their browser (or clicks a link the header, or whatever).

What happens is that when the user clicks the link in the email it takes them to /account/reset_password which looks up their account by the reset code on the link (which was sent in the e-mail) and it logs them in. So, when they decide, "hmmm...I think I'll go visit the homepage instead," the user is now logged in, but has not reset their password.

To me, that seems to present a problem. So, I added a before_filter to my ApplicationController that verifies that all logged in users must have a nil password reset code otherwise they are redirected to /account/change_password. (The password reset code isn't cleared until after the user has successfully changed their password.)

In the ApplicationController I added:
before_filter :ensure_password_reset
and
module AuthenticatedSystem
def ensure_password_reset
redirect_to :controller => :account, :action => :change_password unless reset_password_has_been_changed
end

def reset_password_has_been_changed
if logged_in?
if current_user.password_reset_code.nil?
return true
else
return false
end
else
true
end
end
end

I'm certain that there is a more idiomatic Ruby way to write reset_password_has_been_changed, but I couldn't think of it.

Fixing a Blank Password Bug in Acts As Authenticated

I came across a bug in Acts As Authenticated when users tried to change their passwords. If they submitted the form with nothing in the new or confirm new password text field, then no error was thrown, but the password wasn't changed either.

The problem was in the :if clause on the validates_presence_of validation, password_required?. It was causing the validation not to occur.

    def password_required?
crypted_password.blank? || !password.blank?
end

This code is saying that a password is required in two situations:

  • when the crypted_password is blank -- that situation happens when creating a new user, OR
  • when the class instance variable 'password' is not blank -- this can only happen when the variable has been accessed, such as when attempting to update a password.

The bug is in the test for !password.blank? because it's assuming that the user will enter something as a new password. To resolve that, I changed the code to this:
    def password_required?
crypted_password.blank? || !password.nil?
end

and now the validation is called (and fails) properly. More about this issue can be found in the last few posts on this page.

How To Make the Debugger Work with RadRails

I've finally got the debugger working with Aptana's RadRails.

I've had the debugger working for awhile, but I was experiencing a problem where the current line, i.e. the current execution line, wasn't being highlighted. Actually, the source file of the current line wasn't being even opened.

After trolling around various messages boards, etc., I learned that the bug has been fixed in the latest beta version of RadRails. Here’s a post on how to do that: http://www.aptana.com/forums/viewtopic.php?t=2939

Personally, I had to manually add the update site in order to get it to work, although you might not have that experience. Of course, it took me awhile to figure out how to do this...here you go:


  • Go to Help > Software Updates > Find and Install

  • Select "Search for new features to install" and click "Next"

  • Click the button on the right for "New Remote Site"

  • Enter:

    • Name: RadRails Beta

    • URL: http://update.aptana.com/update/rails/beta/3.2/site.xml


  • Click 'OK'

  • Check the box next to "RadRails Beta"

  • Click the "Finish" button.


Now the update should download and install.

Where to put/store/save/keep your modules and files containing modules?

To a Rails newbie, sometimes the simplest things are hard to figure out. Here's what you need to know:


When you create a module, you save it to your lib/ directory.

All the modules in the lib/ directory are auto-loaded by Rails. That is, Rails does something like this:
for file in lib/
require file
end
Also, I think there is some magic to this, but I'm not 100% sure. If you have a module called MiscUtils then your file needs to be named misc_utils.rb in order for Rails to auto-load it.

Additionally, Ruby does this super-sweet thing where you can re-open any class or module and add to it at any time. In other words, you can declare a class or module in two locations, and Ruby will merge them together and treat them as one class. My experience has been that when you do this, then you need to explicitly require the files even if they're in the lib directory.

What is that hyphen right before the closing of an ERb block?

Periodically, I see some ERb code in a view like this:


<% form_tag '/posts' do -%>

<%= submit_tag 'Save' %>
<% end -%>

In fact, that code was culled right from the Rails docs at for form_tag

As you can see, in those two ERb tags, there is this syntax at close of the tag:
-%>
Today I was wondering what the hyphen (-) was for before the percentage symbol (%). It turns out that the hyphen means that when the HTML output is generated there is no line return after the close of the ERb tag.

For example, the ERb code above produces this HTML:
<form action="/posts" method="post">    <div><input name="commit" type="submit" value="Save" /></div>
</form>

whereas this ERb code:
<% form_tag '/posts' do %>    
<%= submit_tag 'Save' %>
<% end %>

produces this HTML:
<form action="/posts" method="post">
<div><input name="commit" type="submit" value="Save" /></div>
</form>

How Mixins, Include and Extend Work

I was a little puzzled tonight by this chunk of code that I found in the acts_as_authenticated plug-in module:

    def self.included(base)
base.send :helper_method, :current_user, :logged_in?
end

It comes down to some Ruby magic: when a module is included by a class the self.included method on the module is called. Likewise, when a class extends a module the self.extended method is called.

"base" is the class that includes/extends the module. "send" is calling the method ":helper_method" and passing ":current_user" and ":logged_in?" as parameters.

Special thanks to Juixe for an excellent article that helped me figure this out.

DRY Migrations (aka reverting or undoing earlier migrations)

I have a case where I made some database changes in migration 001 and now I want to undo them in migration 005. This is different that actually rolling back to version 001 (i.e. rake db:migrate version=1)...I actually want to undo or revert what I did in 001. The obvious thing to do would be to simply have 005 do the opposite of 001, but that isn't very DRY.

Using a simple example, let's say my migrations were:


  • 001_create_books.rb
  • 002_create_libraries.rb
  • 003_create_librarians.rb

and now my library is going electronic, so I do this:

  • 004_create_e_books.rb
  • 005_destroy_books.rb

In 005 I want to do the exact opposite of 001, so I did this:

class DestroyBooks < ActiveRecord::Migration
def self.up
CreateBooks::migrate(:down)
end

def self.down
CreateBooks::migrate(:up)
end
end

Custom Configurations and App Specific Settings


One not immediately obvious Ruby on Rails configuration issue I came across is how to structure application-specific config parameters, and in particular, how to make them configurable/overridable across different environments (dev, test, production). This has been solved repeatedly in different ways by the Rails community and there's info scattered around but assimilating it took a while, here's what I've settled on for now.


I couldn't have said it better myself. I've now spent 4 hours researching the best way to do this...this is a basic feature of a web app, you'd think there would be a conventional way to create ..whatever you want to call them: custom configurations, application specific settings, application configs...in Rails.

At present, I've found four solutions...the one suggested by the above blogger, and these three others:

  • http://www.taknado.com/2007/7/25/custom-configuration-info-in-rails
  • http://jarmark.org/projects/app-config/
  • Use after_initialize method on the Rails::Configuration class. (Note: this is only semi-well documented...it's documented, but not included at http://api.rubyonrails.org. I found it here: http://edgedocs.planetargon.org/classes/Rails/Configuration.html#M002860)


In addition, I found these blog posts useful:


  • http://toolmantim.com/article/2006/12/27/environments_and_the_rails_initialisation_process
  • http://glu.ttono.us/articles/2006/05/22/guide-environments-in-rails-1-1


I haven't decided how I'm going to do this yet, but I hope you find this helpful.

UPDATE: I was exchanging e-mail from Jeff at softiesonrails.com who suggested this solution:
What I usually do is add it to the bottom of environment.rb. If I have RAILS_ENV-dependent data (like development mode vs. production mode), then just put the relevant Ruby code at the bottom of environments/development.rb, for example:

    module MyConstants
ALLOWED_NAMES = ['jeff', 'cookie monster']
IP_ALLOWED = '1.2.3.4'
end

and then you can access them anywhere in your Rails code as MyConstants::ALLOWED_NAMES, etc.

If you prefer to move it to a file, you'd create a file named my_constants.rb in the /lib folder, and then explicitly require it from environment.rb:

    require 'my_constants'