Module: MixedIdentifierForUserResource

Defined in:
lib/modify_resource/rails/active_record/mixed_identifier_for_user_resource.rb

Instance Method Summary collapse

Instance Method Details

#has_mixed_identifier_for(user_resource, options = {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/modify_resource/rails/active_record/mixed_identifier_for_user_resource.rb', line 2

def has_mixed_identifier_for(user_resource, options={})
  
  user_resource = user_resource.to_s
  
  self.send :attr_accessible, :"#{user_resource}_identifier"
  
  instance_eval <<-END
    validate :"#{user_resource}_identifier", presence: true
  END

  class_eval <<-END
    def #{user_resource}_identifier=(identifier)
      if identifier.is_a? Fixnum or identifier.numeric? or identifier.parameter_id?
        self.#{user_resource}_id = identifier
      else
        # Try to uncover the as_user of either this resource or the parent
        self.#{user_resource} = #{user_resource.classify}.find_or_initialize_by_email(identifier)
      end
    end
    
    def #{user_resource}_identifier
      resource = self.#{user_resource}
      resource.try(:id) || resource.try(:email) || resource.try(:email_address)
    end
    
    def mass_assignment_authorizer(role)
      super(role) << "#{user_resource}_identifier"
    end
    
    before_validation do
      if #{user_resource}.present? and #{user_resource}.new_record? and #{user_resource}.respond_to? :invite!
        #{user_resource}.invite! @as_user
        self.#{user_resource}_id = #{user_resource}.id
      end
    end
  END
  
end