Module: Nifty::KeyValueStore::ModelExtension

Defined in:
lib/nifty/key_value_store/model_extension.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
# File 'lib/nifty/key_value_store/model_extension.rb', line 5

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#get_custom_values_for(group) ⇒ Object

Get the values for a given group as a hash from the database without caching



53
54
55
56
57
58
# File 'lib/nifty/key_value_store/model_extension.rb', line 53

def get_custom_values_for(group)
  nifty_key_value_pairs.where(:group => group).inject({}) do |hash, value|
    hash[value.name] = value.value
    hash
  end
end

#save_custom_values_to_dbObject

Save all custom values in the appropriate methods to the



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/nifty/key_value_store/model_extension.rb', line 61

def save_custom_values_to_db
  # get the existing joins ready
  existing_joins = self.nifty_key_value_pairs
  # go through all groups
  self.class.key_value_stores.each do |group|
    db_values     = get_custom_values_for(group)
    local_values  = self.send(group).delete_if { |k,v| v.blank? }
    
    # remove any keys which no longer exist
    keys_to_remove = db_values.keys - local_values.keys
    self.nifty_key_value_pairs.where(:group => group, :name => keys_to_remove).destroy_all unless keys_to_remove.empty?
    
    # add/update all remaining keys
    local_values.each do |key, value|
      if existing_join = existing_joins.select { |j| j.group == group.to_s && j.name == key}.first
        existing_join.value = value
        existing_join.save
      else
        self.nifty_key_value_pairs.create(:group => group, :name => key, :value => value)
      end
    end
  end
end