Module: ActiveRecord::EavHashes::ClassMethods

Defined in:
lib/eav_hashes/activerecord_extension.rb

Instance Method Summary collapse

Instance Method Details

#eav_hash_for(hash_name, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/eav_hashes/activerecord_extension.rb', line 8

def eav_hash_for (hash_name, options={})
  # Fill in default options not otherwise specified
  options[:hash_name] = hash_name
  options[:parent_class_name] = self.name.to_sym
  options = ActiveRecord::EavHashes::Util::fill_options_hash options

  # Store the options hash in a class variable to create the EavHash object
  # if and when it's actually used.
  class_variable_set "@@#{hash_name}_hash_options".to_sym, options

  # Create the association, the entry update hook, and a helper method to lazy-load the entries
  class_eval "    has_many :\#{options[:entry_assoc_name]}, class_name: \#{options[:entry_class_name]}, foreign_key: \"\#{options[:parent_assoc_name]}_id\", dependent: :delete_all\n    after_save :save_\#{hash_name}\n    def \#{hash_name}\n      @\#{hash_name} ||= ActiveRecord::EavHashes::EavHash.new(self, @@\#{hash_name}_hash_options)\n    end\n\n    def save_\#{hash_name}\n      @\#{hash_name}.save_entries if @\#{hash_name}\n    end\n\n    def self.find_by_\#{hash_name} (key, value=nil)\n      self.find (ActiveRecord::EavHashes::Util::run_find_expression(key, value, @@\#{hash_name}_hash_options))\n    end\n  END_EVAL\nend\n"