Module: CompositePrimaryKeys::ActiveRecord::AttributeMethods::ClassMethods

Defined in:
lib/composite_primary_keys/attribute_methods.rb

Instance Method Summary collapse

Instance Method Details

#define_read_method(symbol, attr_name, column) ⇒ Object

Define an attribute reader method. Cope with nil column.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/composite_primary_keys/attribute_methods.rb', line 11

def define_read_method(symbol, attr_name, column)
  cast_code = column.type_cast_code('v') if column
  cast_code = "::#{cast_code}" if cast_code && cast_code.match('ActiveRecord::.*')
  access_code = cast_code ? "(v=@attributes['#{attr_name}']) && #{cast_code}" : "@attributes['#{attr_name}']"

  unless self.primary_keys.include?(attr_name.to_sym)
    access_code = access_code.insert(0, "missing_attribute('#{attr_name}', caller) unless @attributes.has_key?('#{attr_name}'); ")
  end

  if cache_attribute?(attr_name)
    access_code = "@attributes_cache['#{attr_name}'] ||= (#{access_code})"
  end

  evaluate_attribute_method attr_name, "def #{symbol}; #{access_code}; end"
end

#evaluate_attribute_method(attr_name, method_definition, method_name = attr_name) ⇒ Object

Evaluate the definition for an attribute related method



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/composite_primary_keys/attribute_methods.rb', line 28

def evaluate_attribute_method(attr_name, method_definition, method_name=attr_name)
  unless primary_keys.include?(method_name.to_sym)
    generated_methods << method_name
  end

  begin
    class_eval(method_definition, __FILE__, __LINE__)
  rescue SyntaxError => err
    generated_methods.delete(attr_name)
    if logger
      logger.warn "Exception occurred during reader method compilation."
      logger.warn "Maybe #{attr_name} is not a valid Ruby identifier?"
      logger.warn "#{err.message}"
    end
  end
end