Module: ActiveRecord::Acts::EavModel::ClassMethods

Defined in:
lib/acts_as_eav_model.rb

Instance Method Summary collapse

Instance Method Details

#has_eav_behavior(options = {}) ⇒ Object

This allows you to implement custom methods on the related class by

simply defining the class manually.
  • table_name: The table for the related model. This defaults to the attribute model’s table name.

  • relationship_name: This is the name of the actual has_many relationship. Most of the type this relationship will only be used indirectly but it is there if the user wants more raw access. This defaults to the class name underscored then pluralized finally turned into a symbol.

  • foreign_key: The key in the attribute table to relate back to the model. This defaults to the model name underscored prepended to “_id”

  • name_field: The field which stores the name of the attribute in the related object

  • value_field: The field that stores the value in the related object

  • fields: A list of fields that are valid eav attributes. By default this is “nil” which means that all field are valid. Use this option if you want some fields to go to one flex attribute model while other fields will go to another. As an alternative you can override the #eav_attributes method which will return a list of all valid flex attributes. This is useful if you want to read the list of attributes from another source to keep your code DRY. This method is given a single argument which is the class for the related model. The following provide an example:

class User < ActiveRecord::Base
  has_eav_behavior :class_name => 'UserContactInfo'
  has_eav_behavior :class_name => 'Preferences'

  def eav_attributes(model)
    case model
      when UserContactInfo
        %w(email phone aim yahoo msn)
      when Preference
        %w(project_search project_order user_search user_order)
      else Array.new
    end
  end
end

marcus = User. 'marcus'
marcus.email = '[email protected]' # Will save to UserContactInfo model
marcus.project_order = 'name'     # Will save to Preference
marcus.save # Carries out save so now values are in database

Note the else clause in our case statement. Since an empty array is returned for all other models (perhaps added later) then we can be certain that only the above eav attributes are allowed.

If both a :fields option and #eav_attributes method is defined the fields option take precidence. This allows you to easily define the field list inline for one model while implementing #eav_attributes for another model and not having #eav_attributes need to determine what model it is answering for. In both cases the list of flex attributes can be a list of string or symbols

A final alternative to :fields and #eav_attributes is the #is_eav_attribute? method. This method is given two arguments. The first is the attribute being retrieved/saved the second is the Model we are testing for. If you override this method then the #eav_attributes method or the :fields option will have no affect. Use of this method is ideal when you want to retrict the attributes but do so in a algorithmic way. The following is an example:

class User < ActiveRecord::Base
  has_eav_behavior :class_name => 'UserContactInfo'
  has_eav_behavior :class_name => 'Preferences'

  def is_eav_attribute?(attr, model)
    case attr.to_s
      when /^contact_/ then true
      when /^preference_/ then true
      else
        false
    end
  end
end

marcus = User. 'marcus'
marcus.contact_phone = '021 654 9876'
marcus.contact_email = '[email protected]'
marcus.preference_project_order = 'name'
marcus.some_attribute = 'blah'  # If some_attribute is not defined on
                                # the model then method not found is thrown


205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/acts_as_eav_model.rb', line 205

def has_eav_behavior(options = {})
  Rails.logger.debug("HERE OPTIONS=#{options.inspect}")
  # Provide default options
  options[:class_name] ||= self.name + 'Attribute'
  options[:table_name] ||= options[:class_name].tableize
  options[:relationship_name] ||= options[:class_name].tableize.to_sym
  options[:foreign_key] ||= "#{self.table_name.singularize.downcase}_id" #self.name.foreign_key
  options[:base_foreign_key] ||= self.name.underscore.foreign_key
  options[:name_field] ||= 'name'
  options[:value_field] ||= 'value'
  options[:fields].collect! {|f| f.to_s} unless options[:fields].nil?
  options[:parent] = self.name

  # Init option storage if necessary
  cattr_accessor :eav_options
  self.eav_options ||= Hash.new

  # Return if already processed.
  return if self.eav_options.keys.include? options[:class_name]

  # Attempt to load related class. If not create it
  begin
    options[:class_name].constantize
  rescue
    Object.const_set(options[:class_name],
    Class.new(ActiveRecord::Base)).class_eval do
      def self.reloadable? #:nodoc:
        false
      end
    end
  end

  # Store options
  self.eav_options[options[:class_name]] = options

  # Only mix instance methods once
  unless self.included_modules.include?(ActiveRecord::Acts::EavModel::InstanceMethods)
    send :include, ActiveRecord::Acts::EavModel::InstanceMethods
  end

  # Modify attribute class
  attribute_class = options[:class_name].constantize
  base_class = self.name.underscore.to_sym

  attribute_class.class_eval do
    belongs_to base_class, :foreign_key => options[:base_foreign_key]
    alias_method :base, base_class # For generic access
  end

  # Modify main class
  class_eval do
    has_many options[:relationship_name],
      :class_name => options[:class_name],
      :table_name => options[:table_name],
      :foreign_key => options[:foreign_key],
      :dependent => :destroy

    # The following is only setup once
    unless method_defined? :method_missing_without_eav_behavior

      # Carry out delayed actions before save
      after_validation :save_modified_eav_attributes,:on=>:update
      
      # Make attributes seem real
      alias_method_chain :respond_to?, :eav_behavior
      alias_method_chain :method_missing, :eav_behavior

      private

      alias_method_chain :read_attribute, :eav_behavior
      alias_method_chain :write_attribute, :eav_behavior

    end
  end
  
  create_attribute_table
  
end