Skip to content

Instantly share code, notes, and snippets.

@nicogaldamez
Last active July 18, 2016 18:49
Show Gist options
  • Save nicogaldamez/b4a8a30407ef322c665343decba65dac to your computer and use it in GitHub Desktop.
Save nicogaldamez/b4a8a30407ef322c665343decba65dac to your computer and use it in GitHub Desktop.
Settings as pair value
# ---- Guardar configuraciones como clave-valor en la BD. ----
# Set
# Setting.clave = valor
# Setting[clave] = valor
# Get
# Setting.clave
# Setting[clave]
# Destroy
# Setting.destroy(clave)
# == Schema Information
#
# Table name: settings
#
# id :integer not null, primary key
# var :string(255)
# value :text
# created_at :datetime
# updated_at :datetime
#
class Setting < ActiveRecord::Base
class SettingNotFound < RuntimeError; end
class << self
# get o set de una variable con la variable como nombre de método
def method_missing(method, *args)
method_name = method.to_s
super(method, *args)
rescue NoMethodError
# set del valor a la variable
if method_name[-1] == '='
var_name = method_name.sub('=', '')
value = args.first
self[var_name] = value
else
# recuperar el valor de una variable
self[method_name]
end
end
# elimina la variable
def destroy(var_name)
var_name = var_name.to_s
obj = object(var_name)
raise SettingNotFound, "La variable \"#{var_name}\" no existe" if obj.nil?
obj.destroy
true
end
# accede a una variable a través de la notación []
def [](var_name)
object(var_name).try(:value)
end
# setea una variable a través de la notación []
def []=(var_name, value)
var_name = var_name.to_s
record = object(var_name) || self.new(var: var_name)
record.value = value
record.save!
value
end
def object(var_name)
self.find_by(var: var_name.to_s)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment