Skip to content

Instantly share code, notes, and snippets.

@jagira
Created February 23, 2011 19:58
Show Gist options
  • Save jagira/841051 to your computer and use it in GitHub Desktop.
Save jagira/841051 to your computer and use it in GitHub Desktop.
Template model class for having configurable messages stored in database.
class Template < ActiveRecord::Base
validates_uniqueness_of :name
# Set default values in this hash
DEFAULT_VALUES = {:community => "Ruby on Rails"}
# Find template by its name
# @template = Template.where(:name => "welcome_message").first
# Template has the following message attribute
# @template.message
# => "Hello {user_name}. Thank you for joining {community}."
# Call interpolate method and pass the hash
# @template.interpolate({:user_name => "User Name"})
def interpolate(values)
values = values.reverse_merge! DEFAULT_VALUES
text = message
attr_available.split(',').each do |attr|
text = text.sub("{#{attr}}", values[attr.to_sym])
end
text
end
end
# == Schema Information
#
# Table name: templates
#
# id :integer not null, primary key
# message :text
# attr_available :text
# name :string(255)
# created_at :datetime
# updated_at :datetime
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment