Module: Softwear::Auth::BelongsToUser::ClassMethods

Defined in:
lib/softwear/auth/belongs_to_user.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to_userObject



31
32
33
# File 'lib/softwear/auth/belongs_to_user.rb', line 31

def belongs_to_user
  belongs_to_user_called(:user)
end

#belongs_to_user_called(name, options = {}) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/softwear/auth/belongs_to_user.rb', line 7

def belongs_to_user_called(name, options = {})
  foreign_key = "#{name}_id"

  # Create an anonymous module and include it, so that we can
  # override the generated association methods and call `super`
  # in the method body.
  association_methods = Module.new
  association_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
    def #{name}
      @#{name} ||= User.find(#{name}_id)
    end

    def #{name}=(new)
      self.#{foreign_key} = new.id
      @#{name} = new
    end
  RUBY

  self.user_associations ||= []
  user_associations << name.to_sym

  send(:include, association_methods)
end