Skip to content

Instantly share code, notes, and snippets.

@pnegri
Created April 16, 2012 15:41
Show Gist options
  • Save pnegri/2399514 to your computer and use it in GitHub Desktop.
Save pnegri/2399514 to your computer and use it in GitHub Desktop.
Modelo de Lib para ActiveRecord
# Nao esquecer que para cada modulo voce precisa criar um initializer em config/initializers e fazer o require
# Ex:
# config/initializer/act_as_boiler.rb:
# require 'boiler_model_funcionality'
module BoilerModelFuncionality
# Detectar quando eh feito um include e executar o seguinte abaixo...
# Para usar, incluir manualmente no model que quiser a feature
# Ex: include BoilerModelFuncionality
def self.included(base)
# Isto acontece quando incluimos o Modulo em nosso Model
# Posso chamar qualquer funcao do ActiveRecord (before_filter, etc)
# base.default_values :security_hash => lambda { (SecureRandom.hex(10)[12..-1]).upcase }
# Neste caso iremos extender os metodos do Model com novos metodos estaticos
# Model.a_static_method, lembrando que isto nao funcionaria para uma instancia pois eh estático
base.extend( ClassMethods )
end
module ClassMethods
# Isto soh sera disponivel se o include tiver sido manual
def a_static_method
puts "I am a static Method"
end
end
module MetaProgramming
# Para usar isto, ponha no model:
# act_as_boiler :dokie
# @
# Ele define:
# Instancia.boiler_for_dokie
# Model.static_boiler_for_dokie
#
def act_as_boiler( field_name )
# Define Methods for INSTANCES
define_method "boiler_for_#{field_name}" do
puts "Ok. I am a boiler and my name is: #{field_name}"
end
# Define Methods for CLASSES (SELF)
(class << self; self; end).send(:define_method, "static_boiler_for_#{field_name}") do
# Lembrese, aqui eh estatico, nenhum attributo funcionaria aqui
# Aqui eh possivel chamar where, find_by, order, etc
puts "Ok. I am boiler for the Class (Statics). My name is: #{field_name}"
end
end
end
end
if defined?(ActiveRecord::Base)
# Se preferimos extender todos os models com esta funcionalidade, poderiamos usar
ActiveRecord::Base.extend BoilerModelFuncionality::MetaProgramming
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment