Last active
August 29, 2015 14:08
-
-
Save haslo/c1cb3e549c2a3a8ee576 to your computer and use it in GitHub Desktop.
Getters and Setters for JSON Data Fields for ActiveRecord Models
This file contains hidden or 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 Concerns | |
module ModelWithJSONData | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def json_data_field_descriptions | |
[] | |
end | |
end | |
def method_missing(method, *args, &block) | |
self.class.json_data_field_descriptions.each do |field_description| | |
if field_description[:name].to_s == method.to_s | |
self.class.__send__(:define_method, field_description[:name].to_sym) do | |
self.json_data ||= {} | |
self.json_data[field_description[:name].to_s] | |
end | |
return __send__(field_description[:name]) | |
end | |
if "#{field_description[:name]}=" == method.to_s | |
self.class.__send__(:define_method, "#{field_description[:name]}=".to_sym) do |value| | |
self.json_data ||= {} | |
self.json_data[field_description[:name].to_s] = __send__(field_description[:data_type].name, value) | |
end | |
return __send__("#{field_description[:name]}=", args[0]) | |
end | |
end | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haben das ja schon besprochen, es macht was ganz anderes 😁 Habe das Gist jetzt noch aktualisiert, die JSON-abstrahierten Datenfelder sind jetzt typisiert und validierbar.
https://github.com/haslo/tournament_tool/blob/master/spec/support/model_with_json_examples.rb
https://github.com/haslo/tournament_tool/blob/master/spec/models/concerns/model_with_json_data_spec.rb