ich ein Konfigurationsmodell ähnlich wie diese verwenden:
# == Schema Information
# Schema version: 20081015233653
#
# Table name: configurations
#
# id :integer not null, primary key
# name :string(20) not null
# value :string(255)
# description :text
#
class InvalidConfigurationSym < StandardError; end
class Configuration < ActiveRecord::Base
TRUE = "t"
FALSE = "f"
validates_presence_of :name
validates_uniqueness_of :name
validates_length_of :name, :within => 3..20
# Enable hash-like access to table for ease of use.
# Raises InvalidConfigurationSym when key isn't found.
# Example:
# Configuration[:max_age] => 80
def self.[](key)
rec = self.find_by_name(key.to_s)
if rec.nil?
raise InvalidConfigurationSym, key.to_s
end
rec.value
end
# Override self.method_missing to allow
# instance attribute type access to Configuration
# table. This helps with forms.
def self.method_missing(method, *args)
unless method.to_s.include?('find') # skip AR find methods
value = self[method]
return value unless value.nil?
end
super(method, args)
end
end
Hier ist, wie ich Verwenden Sie es:
class Customer < ActiveRecord::Base
validate :customer_is_old_enough?
def customer_is_old_enough?
min_age = Date.today << (Configuration[:min_age].to_i * 12)
self.errors.add(:dob, "is not old enough") unless self.dob < min_age
end
end
Eine Sache, die ich nicht ganz glücklich bin mit muss #to_i
wie in der Probe anrufen, aber da es für mich so weit funktioniert, habe ich nicht zu viel darüber nachgedacht, es neu zu entwerfen.
Doh! Ich habe Matt Haleys Antwort im Grunde genommen dupliziert. Nun, ich schätze, meine Antwort ist eine Zusammenfassung des gesamten Codes, den er eingeführt hat, ohne dem faulen/zufälligen Leser (mir) zu sagen, wohin er gehen würde. – Roboprog