我有一个ActiveRecord类,它的属性是一个数组(Postgres数组列),我希望数组中的项是唯一的。什么是覆盖阵列本身发生的方法的最佳方法,例如#<< ?
def encrypt(text, key, direction):
if direction == 1: #The direction is either -1, or 1. If it is 1, it goes right. Otherwise, it will go left.
emptys=''
for x in text:
b = ord(x) #b is the individual characters after the ord() function
b+=key
if b<=122:
n = chr(b) #n is the converted letter of the encrypted ASCII number
emptys+=n
else:
o=b-90
q=chr(o)
emptys+=q
return emptys
else:
emptys=''
for x in text:
b = ord(x) #b is the individual characters after the ord() function
b=b-key
if b>=32:
n = chr(b) #n is the converted letter of the encrypted ASCII number
emptys+=n
else:
o=b+90
q=chr(o)
emptys+=q
return emptys
答案 0 :(得分:2)
当您撰写r.tags << value
时,您也可以看到r.tags.<<(value)
。 tags
方法将返回Array
的实例,然后会发生这种情况:array.<<(value)
数组将接收<<
方法,而不是tags
属性。
您必须覆盖<<
上的Array
方法。
最好退一步到r
对象并向add_tags
添加Rule
方法以实现您提出的逻辑。你要求的是可能的,但实施起来要比这更复杂:
module PgTags
def tags=(value)
write_attribute :tags, value.uniq
end
def add_tags(*t)
self.tags = (tags << t).flatten.uniq
end
end
class Rule < ActiveRecord::Base
include PgTags
end
r = Rule.new
r.tags = %w(one two one)
puts r.tags #=> ['one', 'two']
r.tags.add_tags 'one'
r.tags.add_tags 'three'
puts r.tags #=> ['one', 'two', 'three']
add_tags
方法的行为与您使用<<
时的预期相同,只是它处理uniq逻辑并将新值分配给规则自己的tags
} attribute。
答案 1 :(得分:0)
另一种方法(现在我认为这是Postgres)会:
<<
这样可以将=
和MYSQL
功能内置到AR中。