Module: CompositePrimaryKeys::ActiveRecord::AttributeMethods

Defined in:
lib/composite_primary_keys/attribute_methods.rb

Overview

:nodoc:

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_id, *args, &block) ⇒ Object

Allows access to the object attributes, which are held in the @attributes hash, as though they were first-class methods. So a Person class with a name attribute can use Person#name and Person#name= and never directly use the attributes hash – except for multiple assigns with ActiveRecord#attributes=. A Milestone class can also ask Milestone#completed? to test that the completed attribute is not nil or 0.

It’s also possible to instantiate related objects, so a Client class belonging to the clients table with a master_id foreign key can instantiate master through Client#master.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/composite_primary_keys/attribute_methods.rb', line 54

def method_missing(method_id, *args, &block)
  method_name = method_id.to_s

  # If we haven't generated any methods yet, generate them, then
  # see if we've created the method we're looking for.
  if !self.class.generated_methods?
    self.class.define_attribute_methods

    if self.class.generated_methods.include?(method_name)
      return self.send(method_id, *args, &block)
    end
  end

  if self.class.primary_keys.include?(method_name.to_sym)
    ids[self.class.primary_keys.index(method_name.to_sym)]
  elsif md = self.class.match_attribute_method?(method_name)
    attribute_name, method_type = md.pre_match, md.to_s
    if @attributes.include?(attribute_name)
      __send__("attribute#{method_type}", attribute_name, *args, &block)
    else
      super
    end
  elsif @attributes.include?(method_name)
    read_attribute(method_name)
  else
    super
  end
end

Class Method Details

.append_features(base) ⇒ Object



4
5
6
7
# File 'lib/composite_primary_keys/attribute_methods.rb', line 4

def self.append_features(base)
  super
  base.send(:extend, ClassMethods)
end