module Merb class Request def initialize(env, method) @env = env @method = method end # returns true if the request is an ajax request. def xml_http_request? not /XMLHttpRequest/i.match(@env['HTTP_X_REQUESTED_WITH']).nil? end alias xhr? :xml_http_request? alias ajax? :xml_http_request? # returns the remote IP address if it can find it. def remote_ip return @env['HTTP_CLIENT_IP'] if @env.include?('HTTP_CLIENT_IP') if @env.include?(Mongrel::Const::HTTP_X_FORWARDED_FOR) then remote_ips = @env[Mongrel::Const::HTTP_X_FORWARDED_FOR].split(',').reject do |ip| ip =~ /^unknown$|^(127|10|172\.16|192\.168)\./i end return remote_ips.first.strip unless remote_ips.empty? end return @env[Mongrel::Const::REMOTE_ADDR] end # returns either 'https://' or 'http://' depending on # the HTTPS header def protocol ssl? ? 'https://' : 'http://' end # returns true if the request is an SSL request def ssl? @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https' end # returns he request uri. def uri @env['REQUEST_URI'] end # returns the uri without the query string. def path uri ? uri.split('?').first : '' end # returns the PATH_INFO def path_info @env['PATH_INFO'] end # returns the port the server is running on def port @env['SERVER_PORT'].to_i end # returns the full hostname including port def host @env['HTTP_X_FORWARDED_HOST'] || @env['HTTP_HOST'] end # returns an array of all the subdomain parts of the host. def subdomains(tld_length = 1) parts = host.split('.') parts[0..-(tld_length+2)] end # returns the full domain name without the port number. def domain(tld_length = 1) host.split('.').last(1 + tld_length).join('.').sub(/:\d+$/,'') end # returns the REQUEST_METHOD def method @method ||= @env['REQUEST_METHOD'] end # create predicate methods for querying the REQUEST_METHOD [:get, :post, :put, :delete, :head].each do |m| eval %{ def #{m}?; method == :#{m}; end } end end end