我的应用程序中未定义的方法。怎么了?

时间:2009-04-08 05:17:26

标签: ruby-on-rails ruby

我尝试在我的应用中阻止IP地址 - lifeonrails.org。我已经在/ lib和model banned_ip中有一个模块。

为什么我在views / banned_ips / index.html下面出现此错误?

===我的错误:===

管理员/ banned_ips #index

中的

NoMethodError

显示app / views / admin / banned_ips / index.html.erb第9行引发:

undefined method `banned?' for "127.0.0.1":String

提取的来源(第9行):

6:     <th>Last_ip</th>
7:     <th>Date</th>
8:   </tr>
9: <% if request.remote_ip.banned? == true %>banned<% else %>ok<% end %>
10: <% for banned_ip in @banned_ips %>
11:   <tr>
12:     <td><%=h banned_ip.first_ip %></td>

=== / lib ===

中的模块infrid.rb
module Infrid
  class IPAddress
    include Comparable
    def initialize(address)
      @address = address
    end
    def split
      @address.split(‘.‘).map {|s| s.to_i }
    end
    def <=>(other)
      split <=> other.split
    end
    def to_s
      @address
    end
  end
end

===模型banned_ip:===

class BannedIp < ActiveRecord::Base
    @banned_ips # hash of ips and masks
    validates_presence_of :first_ip, :message =>"first address is needed"
    validates_presence_of :last_ip, :message =>"last address is needed"
    validates_format_of :first_ip, :with => REG_IP, :message => "is invalid (must be x.x.x.x where x is 0-255)", :if => Proc.new {|ar| !ar.first_ip.blank? }
    validates_format_of :last_ip, :with => REG_IP, :message => "is invalid (must be x.x.x.x where x is 0-255)", :if => Proc.new {|ar| !ar.last_ip.blank? }

    def self.banned?(ip)
      reload_banned_ips if @banned_ips.nil?
      begin
          ip = Infrid::IPAddress.new(ip)
          @banned_ips.each { |b|
            return true if ip.between?(b[0], b[1])
          }
      rescue
          logger.info "IP FORMAT ERROR"
          return true
      end
      false
    end
    def self.banned_ips
        reload_banned_ips if @banned_ips.nil?
        @banned_ips.collect {|b| b[0].to_s + ".." + b[1].to_s }.join"\n"
    end
    #keeps a cache of all banned ip ranges
    def self.reload_banned_ips
      r = connection.select_all("select first_ip, last_ip from banned_ips")
      if !r
        @banned_ips=[] 
      end
      @banned_ips = r.map {|item| [Infrid::IPAddress.new(item["first_ip"]),Infrid::IPAddress.new(item["last_ip"])] }
    end
end

2 个答案:

答案 0 :(得分:2)

request.remote_ip以字符串形式返回IP地址,而字符串没有banned?方法。看起来你想要BannedIP.banned?(request.remote_ip)

答案 1 :(得分:2)

您的问题是,您试图通过banned?致电String,而不是BannedIp课程。你有两个解决方案。

  1. 替换代码以使用BannedIp.banned?(request.remote_ip)
  2. 检查禁止的IP
  3. 将方法修补到字符串类中,该类为您调用类方法,这是在rails stype中但不太可读。
  4. 需要这个。 (bug阻止代码块工作)

    class String
      def banned?
        BannedIp.banned?(self)
      end
    end