我正在尝试写一个类来存储禁令。我想检查某个IP是否被禁止并返回@ip
,@time
,@reason
等。
class BannedIP
attr_reader :ip, :time, :reason
def initialize(ip, time, reason)
@ip = ip
@time = time
@reason = reason
end
def banned?(ip)
# What do I use here?
end
end
我需要# What do I use here?
部分的帮助,以便我可以执行以下操作:
if b = BannedIP.banned? '10.10.10.10'
答案 0 :(得分:2)
我不确定当你已经知道ip
有意义时回归ip
,但是任何......
您可以使用自定义哈希类:
class BannedHash < Hash
def ban(ip, time, reason)
self[ip] = {time: time, reason: reason}
end
def banned?(ip)
if self.include?(ip)
self[ip]
else
"ip: #{ip} not found."
end
end
end
用法:
def main
b = BannedHash.new
b.ban("10.10.10.10", Time.now, "Some reason")
puts b.banned?("10.10.10.10")
puts b.banned?("11.11.11.11")
end
输出:
{:time=>2015-04-27 21:18:39 +1200, :reason=>"Some reason"}
ip: 11.11.11.11 not found.
答案 1 :(得分:0)
安装mysql2和活动记录宝石
gem install mysql2
gem install active_record
然后执行以下代码快照
require 'active_record'
require 'mysql2'
SOURCE_CREDNTIALS = {
:adapter => "mysql2",
:host => "localhost",
:username => "root",
:password => "password",
:database => "banned_db"
}
class Banned < ActiveRecord::Base
ActiveRecord::Base.establish_connection(SOURCE_CREDNTIALS)
#attr_accessor :id, :ip, :banned_at, :reason
def self.banned?(ip)
where(ip: ip).count > 0
end
end
现在你可以使用这个简单的类作为
user_foo = Banned.create(ip: '10.10.10.10', banned_at: Time.now, reason: 'violated terms and conditions')
Banned.banned?('10.10.10.10')
BannedIP.banned?方法将返回true或false,具体取决于是否禁止特定ip。
答案 2 :(得分:0)
TextBox1.TextChanged