Module: AttrPrivate::SingletonMethods

Defined in:
lib/attr_private.rb

Overview

This provides the ability to mark a field on a record as private, preventing access from outside an instance of the class.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#attr_private(*fields) ⇒ Object



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
40
41
42
43
44
45
46
# File 'lib/attr_private.rb', line 13

def attr_private(*fields)

  write_inheritable_attribute :private_fields, fields
  class_inheritable_reader :private_fields

  extend ClassMethods

  fields.each {|field|
    begin
      column = connection.columns(table_name, "AttrPrivate").detect{|column| column.name.to_sym == field.to_sym} 
    rescue => e
      # If an error occurs looking up the column, we're probably in a context where the db isn't populated.  
      # Do nothing.
      next
    end
    raise ActiveRecord::ActiveRecordError, "Unknown field #{field}" if column.nil?

    # prevent bulk assignment
    attr_protected field
    
    # prevent use of the standard accessors
    module_eval "      def \#{field}\n        raise ::NoMethodError, \"undefined method \\`\#{field}' for \\\#{self}\"\n      end\n      def \#{field}=(x)\n        raise ::NoMethodError, \"undefined method \\`\#{field}=' for \\\#{self}\"\n      end\n      def \#{field}?\n        raise ::NoMethodError, \"undefined method \\`\#{field}?' for \\\#{self}\"\n      end\n    end_eval\n  }\nend\n", __FILE__, __LINE__