Skip to content

Instantly share code, notes, and snippets.

@ohadlevy
Created March 10, 2016 09:41
Show Gist options
  • Select an option

  • Save ohadlevy/bd6a826f42d4952f3c71 to your computer and use it in GitHub Desktop.

Select an option

Save ohadlevy/bd6a826f42d4952f3c71 to your computer and use it in GitHub Desktop.
module Settings
class Mail
include ActiveModel::Validations
include ActiveModel::Model
ATTRIBUTES = [ :administrator, :email_reply_address, :email_subject_prefix, :send_welcome_email ]
attr_accessor *ATTRIBUTES
validates :administrator, :email_reply_address, :format => {
:with => /\A(([\w!#\$%&\'\*\+\-\/=\?\^`\{\|\}~]+((\.\"[\w!#\$%&\'\*\+\-\/=\?\^`\{\|\}~\"\(\),:;<>@\[\\\] ]+(\.[\w!#\$%&\'\*\+\-\/=\?\^`\{\|\}~\"\(\),:;<>@\[\\\] ]+)*\")*\.[\w!#\$%&\'\*\+\-\/=\?\^`\{\|\}~]+)*)|(\"[\w !#\$%&\'\*\+\-\/=\?\^`\{\|\}~\"\(\),:;<>@\[\\\] ]+(\.[\w !#\$%&\'\*\+\-\/=\?\^`\{\|\}~\"\(\),:;<>@\[\\\] ]+)*\"))
@[a-z0-9]+((\.[a-z0-9]+)*|(\-[a-z0-9]+)*)*\z/ix }
def initialize(attributes = {})
super(attributes)
initialize_settings
end
def save
Setting.update(*updated_attributes) if valid?
end
private
def updated_attributes
settings = {}
ATTRIBUTES.each do |name|
setting = record_for(name)
if setting.nil?
raise "unable to find setting: #{name}"
else
settings[setting.id] = {:value => send(name) }
end
end
return [settings.keys, settings.values]
end
def record_for(setting_name)
db_records.detect {|s| setting_name.to_s == s.name}
end
def db_records
@db_records ||= Setting.where(:name => ATTRIBUTES)
end
def initialize_settings
db_records.each do |setting|
send("#{setting.name}=", setting.value)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment