Last active
December 20, 2015 21:49
-
-
Save coderhs/6200809 to your computer and use it in GitHub Desktop.
Conversion using marshaling and JSON load
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
# To store the application settings in a key value pair | |
# Type will store the data type so that the conversion can be | |
# done within the model before send | |
class Temp | |
include DataMapper::Resource | |
# Primary (serial) key | |
property :id, Serial | |
# Non-key columns | |
property :name, String, required: true, unique: true | |
property :value, Text | |
property :conversion, ExtendedEnum[:json, :marshal], labels: ["json", "marshal"], index: true, default: :json | |
# Hook | |
before :save, :change_spaces_to_underscores | |
def change_spaces_to_underscores | |
self.name = self.name.downcase.gsub(' ','_') | |
end | |
class <<self | |
# To retrieve data | |
# Setting['organization_name'] | |
def [](key) | |
data = self.first(name:key) | |
return nil unless data | |
if data.conversion == :json | |
JSON.load(data.value)['value'] | |
else | |
Marshal::load(data.value) | |
end | |
end | |
# To store data | |
# Setting['organization_name']='support sages' | |
def []=(key,object) | |
class_names = [Symbol, Fixnum, String, Float] | |
symbol = nil | |
if object.class == Array then | |
object.each do |item| | |
raise "Invalid Data format stored to Model Hash" unless class_names.include?(item.class) | |
symbol = true if item.class == Symbol | |
end | |
if symbol | |
save_as_marshal key, object | |
else | |
save_as_json key, object | |
end | |
else | |
raise "Invalid Data format stored to Model Hash" unless class_names.include?(object.class) | |
return save_as_marshal(key, object) if object.class == Symbol | |
save_as_json key, object | |
end | |
end | |
private | |
def save_as_marshal key, object | |
self.update_or_create({name:key}, {name:key, value:Marshal::dump(object), conversion: :marshal }) | |
end | |
def save_as_json key, object | |
json_data = Hash.new | |
json_data[:value] = object | |
self.update_or_create({name:key}, {name:key, value:json_data.to_json, conversion: :json}) | |
end | |
protected | |
def update_or_create(conditions = {}, attributes = {}, merger = true) | |
begin | |
if (row = first(conditions)) | |
row.update(attributes) | |
row | |
else | |
create(merger ? (conditions.merge(attributes)) : attributes ) | |
end | |
rescue | |
false | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment