Module: ActiveRecord::Has::CustomFields::ClassMethods

Defined in:
lib/has_custom_fields.rb

Instance Method Summary collapse

Instance Method Details

#custom_field_fields(scope, scope_id) ⇒ Object



194
195
196
197
198
# File 'lib/has_custom_fields.rb', line 194

def custom_field_fields(scope, scope_id)
  options = custom_field_options[self.name]
  klass = Object.const_get(options[:fields_class_name])
  return klass.send("find_all_by_#{scope}_id", scope_id, :order => :id)
end

#has_custom_fields(options = {}) ⇒ Object

Will make the current class have eav behaviour.

The following options are available on for has_custom_fields to modify the behavior. Reasonable defaults are provided:

  • value_class_name: The class for the related model. This defaults to the model name prepended to “Attribute”. So for a “User” model the class name would be “UserAttribute”. The class can actually exist (in that case the model file will be loaded through Rails dependency system) or if it does not exist a basic model will be dynamically defined for you. 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



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/has_custom_fields.rb', line 84

def has_custom_fields(options = {})

  # Provide default options
  options[:fields_class_name] ||= self.name + 'Field'
  options[:fields_table_name] ||= options[:fields_class_name].tableize
  options[:fields_relationship_name] ||= options[:fields_class_name].tableize.to_sym

  options[:values_class_name] ||= self.name + 'Attribute'
  options[:values_table_name] ||= options[:values_class_name].tableize
  options[:relationship_name] ||= options[:values_class_name].tableize.to_sym

  options[:foreign_key] ||= self.name.foreign_key
  options[:base_foreign_key] ||= self.name.underscore.foreign_key
  options[:name_field] ||= 'name'
  options[:value_field] ||= 'value'
  options[:parent] = self.name

  ::Rails.logger.debug("OPTIONS: #{options.inspect}")
  puts("OPTIONS: #{options.inspect}")

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

  # Return if already processed.
  return if self.custom_field_options.keys.include? options[:values_class_name]

  # Attempt to load related class. If not create it
  begin
    Object.const_get(options[:values_class_name])
  rescue
    Object.const_set(options[:fields_class_name],
      Class.new(::CustomFields::CustomFieldBase)).class_eval do
        set_table_name options[:fields_table_name]
        def self.reloadable? #:nodoc:
          false
        end
      end
    ::CustomFields.const_set(options[:fields_class_name], Object.const_get(options[:fields_class_name]))

    Object.const_set(options[:values_class_name],
    Class.new(ActiveRecord::Base)).class_eval do
      cattr_accessor :custom_field_options
      belongs_to options[:fields_relationship_name],
        :class_name => '::CustomFields::' + options[:fields_class_name].singularize
      alias_method :field, options[:fields_relationship_name]
      
      def self.reloadable? #:nodoc:
        false
      end
      
      def validate
        field = self.field
        raise "Couldn't load field" if !field

        if field.style == "select" && !self.value.blank?
          # raise self.field.select_options.find{|f| f == self.value}.to_s
          if field.select_options.find{|f| f == self.value}.nil?
            raise "Invalid option: #{self.value}.  Should be one of #{field.select_options.join(", ")}"
            self.errors.add_to_base("Invalid option: #{self.value}.  Should be one of #{field.select_options.join(", ")}")
            return false
          end
        end
      end
    end
    ::CustomFields.const_set(options[:values_class_name], Object.const_get(options[:values_class_name]))
  end

  # Store options
  self.custom_field_options[self.name] = options

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

  # Modify attribute class
  attribute_class = Object.const_get(options[:values_class_name])
  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[:values_class_name],
      :table_name => options[:values_table_name],
      :foreign_key => options[:foreign_key],
      :dependent => :destroy

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

      # Carry out delayed actions before save
      after_validation :save_modified_custom_field_attributes, :on => :update

      private

      alias_method_chain :read_attribute, :custom_field_behavior
      alias_method_chain :write_attribute, :custom_field_behavior
    end
  end
  
  create_attribute_table
  
end