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
47
48
49
50
51
52
53
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
|
# File 'lib/pgcrypto.rb', line 22
def pgcrypto(*pgcrypto_column_names)
options = pgcrypto_column_names.last.is_a?(Hash) ? pgcrypto_column_names.pop : {}
options = {:include => false, :type => :pgp}.merge(options)
has_many :pgcrypto_columns, :as => :owner, :autosave => true, :class_name => 'PGCrypto::Column', :dependent => :delete_all
hooks do
before(:reload) do
self.class.pgcrpyto_columns.each do |column_name, options|
reset_attribute! column_name
changed_attributes.delete(column_name)
end
end
end
pgcrypto_column_names.map(&:to_s).each do |column_name|
PGCrypto[table_name][column_name] = options.symbolize_keys
start_line = __LINE__; pgcrypto_methods = <<-PGCRYPTO_METHODS
def #{column_name}
return @_pgcrypto_#{column_name}.try(:value) if defined?(@_pgcrypto_#{column_name})
@_pgcrypto_#{column_name} ||= select_pgcrypto_column(:#{column_name})
@_pgcrypto_#{column_name}.try(:value)
end
# We write the attribute directly to its child value. Neato!
def #{column_name}=(value)
attribute_will_change!(:#{column_name}) if value != @_pgcrypto_#{column_name}.try(:value)
if value.nil?
pgcrypto_columns.select{|column| column.name == "#{column_name}"}.each(&:mark_for_destruction)
remove_instance_variable("@_pgcrypto_#{column_name}") if defined?(@_pgcrypto_#{column_name})
else
@_pgcrypto_#{column_name} ||= pgcrypto_columns.select{|column| column.name == "#{column_name}"}.first || pgcrypto_columns.new(:name => "#{column_name}")
pgcrypto_columns.push(@_pgcrypto_#{column_name})
@_pgcrypto_#{column_name}.value = value
end
end
def #{column_name}_changed?
changed.include?(:#{column_name})
end
PGCRYPTO_METHODS
class_eval pgcrypto_methods, __FILE__, start_line
end
if PGCrypto[table_name].any?{|column, options| options[:include] }
default_scope includes(:pgcrypto_columns)
end
end
|