Created
August 21, 2013 20:01
-
-
Save bleakwood/6299432 to your computer and use it in GitHub Desktop.
a module used on models to allow storage of one hash containing multiple key-value pairs in one column "data", for each data fields passed with has_data_fields (see blood_pressure.rb as an example), it creates getter and setter methods, and delegate those methods to data.m, which will be taken care of by the hashie gem, which is a gem allows you…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module NormalizedModel | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def has_data_fields(fields) | |
include Cloud2Health::NormalizedModel::InstanceMethods | |
serialize :data | |
before_validation :set_data | |
class_attribute :data_fields | |
self.data_fields = fields | |
fields.each do |m| | |
attr_reader m | |
delegate m, :to => :data | |
define_method("#{m}="){|value| instance_variable_set("@#{m}_setter".to_sym, value) } | |
end | |
end | |
end | |
module InstanceMethods | |
def set_data | |
self.data = Hashie::Mash.new unless data.is_a?(Hashie::Mash) | |
self.class.data_fields.each do |field| | |
value = instance_variable_get("@#{field}_setter") | |
self.data.send("#{field}=", value) if value | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send(:include, Cloud2Health::NormalizedModel) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment